语句是:编写一个读取整数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&amp; 2它打印前2个素数,N = 3&amp; 4,它打印前3个素数,N = 5&amp; 6,它打印前4个素数,依此类推。这段代码有什么问题?
答案 0 :(得分:5)
我认为您的程序存在许多缺陷需要修复,因此我决定编写一个更简单,更优雅的程序。
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.
}
答案 1 :(得分:2)
// Java Program to generate first 'N' Prime Numbers
public class prime
{
public static void main(String[]args)
{
int count = 0, max_count = 100, i;
System.out.println("First "+max_count+" Prime Numbers:");
for(int num=1; count<max_count; num++)
{
for(i=2; num%i != 0; i++);
if(i == num)
{
System.out.print(" "+num);
count++;
}
}
}
}
答案 2 :(得分:0)
其他人编写了比你更好的代码,我将解释为什么你的代码不起作用。
您没有搜索第一个N素数,您正在搜索素数到N + 2。在您的代码中,x
从2开始,然后上升到N + 2。
如果要查找N个第一个素数,必须在N不等于0时循环,并在每次找到素数时减少N.
(等待这个问题是从2015年开始......该死的)
答案 3 :(得分:0)
使用动态编程:
任何非素数的数字总是可以被数字序列中至少一个素数整除。 如果任何数字不能与之前的所有素数分开,则该数字也是素数
void printPrimeNumbers(int n) {
ArrayList<Integer> primeNumbers = new ArrayList<>();
primeNumbers.add(2);
for (int i = 3; i < n; i+=2) { // skip over even numbers since they are not prime
boolean isPrime = true;
for (Integer prime : primeNumbers) { // check current prime numbers to see if it evenly divides into number
if (i % prime == 0) { // when number is not prime
isPrime = false;
break; // optimization: stop checking when number is already not prime
}
}
if (isPrime) {
primeNumbers.add(i);
}
}
System.out.println(primeNumbers);
}
答案 4 :(得分:0)
public static void main(String... commandline_args)
{
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the limit of prime nos");
int limit=Integer.parseInt(br.readLine());
int checkLimit=0;
int check=0;
outer: for(int i=2;;i++){
check=0;
for(int j=1;j<=i;j++)
{
if(i%j==0)
{
check++;
}
}
if(check==2)
{
checkLimit++;
System.out.println(i);
if(checkLimit==limit) break outer;
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}