[英]prime number checker java
我寫了一個程序來檢查數字是否為素數。 我想使用以下方法檢查數字是否為質數:對於數字P,請使用p-1的階乘,然后將1加到結果中。 最后將結果除以p。 對於不知道的劑量,如果結果為整數,則為質數。
無論如何,我的代碼可以處理的最大質數為167,但是對於任何大於167的數字,我都會遇到NaN錯誤。
有人能發現出什么毛病嗎?
import java.util.Scanner;
public class work {
public static void main(String arg[]) {
System.out.println("Please enter a number to check if its a prime");
Scanner in = new Scanner( System.in );
int num = in.nextInt();
double t = 1;
for (int i=1; i<num; i++){
t = i * t;
}
t = t+1;
t = t / num;
System.out.println(t%1);
if ((t%1 ==0.0) && (t!= 2)){
System.out.println("it is prime");
}
else{
System.out.println("it is not a prime");
}
}
}
好吧,雙精度變量可以容納的數字是有限的。 166! 是大量的。 最大的兩倍是1.7976931348623157E308
。 170! 是7.257415615307994E306
。
您可以改用BigInteger。
static boolean isPrime(long n) {
BigInteger num = BigInteger.valueOf(n);
BigInteger t = BigInteger.ONE;
for (BigInteger i = BigInteger.ONE; i.compareTo(num) < 0; i = i.add(BigInteger.ONE))
t = t.multiply(i);
t = t.add(BigInteger.ONE);
return t.mod(num).equals(BigInteger.ZERO);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.