我正在尝试计算素数,我已经完成了.但我想计算并打印第n个素数(用户输入),在计算其余部分(它们不会被打印)时,只打印第n个素数.
这是我到目前为止所写的内容:
import java.util.Scanner;
/**
* Calculates the nth prime number
* @author {Zyst}
*/
public class Prime {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n,
i = 2,
x = 2;
System.out.printf("This program calculates the nth Prime number\n");
System.out.printf("Please enter the nth prime number you want to find: ");
n = input.nextInt();
for(i = 2, x = 2; i <= n; i++) {
for(x = 2; x < i; x++) {
if(i % …
Run Code Online (Sandbox Code Playgroud) 首先 - 我在这个论坛上检查了很多,但我找不到足够快的东西.我尝试创建一个函数,返回指定范围内的素数.例如,我使用Eratosthenes的筛子完成了这个功能(在C#中).我也试过阿特金的筛子但是Eratosthenes的跑得更快(在我的实施中):
public static void SetPrimesSieve(int Range)
{
Primes = new List<uint>();
Primes.Add(2);
int Half = (Range - 1) >> 1;
BitArray Nums = new BitArray(Half, false);
int Sqrt = (int)Math.Sqrt(Range);
for (int i = 3, j; i <= Sqrt; )
{
for (j = ((i * i) >> 1) - 1; j < Half; j += i)
Nums[j] = true;
do
i += 2;
while (i <= Sqrt && Nums[(i >> 1) - 1]);
}
for …
Run Code Online (Sandbox Code Playgroud)