This question already has answers here:
Calculating and printing the nth prime number
(11个答案)
2年前关闭。
该语句是:编写一个程序,该程序读取整数N并打印前N个素数。
当我运行这段代码时,并没有给出确切的N个数字。例如,对于N = 1和2,它打印前2个素数,对于N = 3和4,它打印前3个素数,对于N = 5和6,它打印前4个素数,依此类推。此代码有什么问题?
(11个答案)
2年前关闭。
该语句是:编写一个程序,该程序读取整数N并打印前N个素数。
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int N = scan.nextInt();
int x = 2;
for(int i = 0; i <= N; i++)
{
int count = 0;
for(int j = 1; j <= x; j++)
if(x%j == 0)
count++;
if(count == 2)
System.out.print(x + " ");
x++;
}
}
当我运行这段代码时,并没有给出确切的N个数字。例如,对于N = 1和2,它打印前2个素数,对于N = 3和4,它打印前3个素数,对于N = 5和6,它打印前4个素数,依此类推。此代码有什么问题?
最佳答案
我认为您的程序中有许多缺陷需要修复,因此我决定编写一个更简单,优雅的程序。
Scanner scan = new Scanner(System.in);
int N = Integer.parseInt( scan.nextLine());
int count = 0;
int num = 2;
while(count != N) { // while count!= number of prime numbers entered keep searching..
boolean prime = true;// to determine whether the number is prime or not
for (int i = 2; i <= Math.sqrt(num); i++) { //efficiency matters
if (num % i == 0) {
prime = false; // if number divides any other number its not a prime so set prime to false and break the loop.
break;
}
}
if (prime) {
count++;
System.out.println(num);
}
num++; see if next number is prime or not.
}
关于java - 打印前N个质数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33725505/
10-12 17:42