为了避免任何误解,我在这里是新手,仍然是Java的初学者。我试图编写一个打印10,001st素数的代码。代码当前检查数字是否可以被数字2-9(包括)整除,然后检查数字的平方根是否是整数。查找10001素数 - 代码没有返回正确的数字
public static void main(String[] args){
Integer Num , Counter;
Double Sqrt; //square root
Num=8;
Counter=4 ;
while(Counter<10001){
Num++;
if ((Num%2!=0) && (Num%3!=0) && (Num%4!=0) && (Num%5!=0) && (Num%6!=0) && (Num%7!=0) && (Num%8!=0) && (Num%9!=0)){
Sqrt = Math.sqrt(Num);
if(Sqrt%1!=0){
Counter++;
}
}
}
System.out.println(Num);
}
}
编辑:
我改变它,使它不再使用假的定义,但是这个新的代码没有输出,我没有看到与循环的任何问题。我也会尝试下面的其他建议,但想知道如何解决这个问题。
public static void main(String[] args)
{
int Num , Counter;
double Sqrt; //square root
Num=1;
Counter=0 ;
while(Counter<10001){
Num++;
Sqrt = Math.sqrt(Num);
int i = (int)Sqrt;
while(i>1){
if(Num%i==0){ //if the number is divisible then the loop is terminated and next number is tested
i=0;
}
i--;
}
if(i==1){
Counter++;
}
}
System.out.println(Num);
}
}
谢谢。
你的算法不正确。考虑数字11x13 = 143,这显然不是素数,不是方数,也不能被2,3整除。 –
@Michael谢谢你指出。我现在正在使用不同的算法。如果你可以看看它,那会很好。 – Abdul97