Java 使用BigInteger进行素数检查(参数不匹配)
我正在尝试做一个应用程序来检查一个特定的数字是否是素数。 因为这个数字大于int或long的值,所以我不得不使用BigInteger,但我对它知之甚少,所以我很恼火。 我要做的是检查n是否可以被奇数(I)除,直到我到达n的根。n(10^24+7)的值是一个素数,我想检查更大的数字,比如10^128+7。我非常感谢你的帮助Java 使用BigInteger进行素数检查(参数不匹配),java,for-loop,primes,biginteger,Java,For Loop,Primes,Biginteger,我正在尝试做一个应用程序来检查一个特定的数字是否是素数。 因为这个数字大于int或long的值,所以我不得不使用BigInteger,但我对它知之甚少,所以我很恼火。 我要做的是检查n是否可以被奇数(I)除,直到我到达n的根。n(10^24+7)的值是一个素数,我想检查更大的数字,比如10^128+7。我非常感谢你的帮助 import javax.swing.*; import java.math.*; public class prime { public static void m
import javax.swing.*;
import java.math.*;
public class prime {
public static void main(String[] args) {
BigInteger n = new BigInteger("1000000000000000000000007");
BigInteger h = new BigInteger("2");
int r;
for(BigInteger i = new BigInteger("3");n.compareTo(i.multiply(BigInteger.valueOf(i)))>=0;i.add(BigInteger.valueOf(h))) {
if(n.divideAndRemainder(i)==0){
r=0;
}else{
r=1;}
}
if(r=0){
System.out.println("not prime");}else{
System.out.println("prime");}
}
}
正确的操作是(您只关心其余部分)或使用。最好将逻辑提取到方法中。大概
static boolean isPrime(BigInteger n) {
BigInteger TWO = BigInteger.ONE.add(BigInteger.ONE);
if (n.mod(TWO).equals(BigInteger.ZERO)) {
return false;
}
BigInteger h = TWO.add(BigInteger.ONE);
// for (; h * h < n; h += 2)
for (; h.multiply(h).compareTo(n) < 0; h = h.add(TWO)) {
if (n.mod(h).equals(BigInteger.ZERO)) {
return false;
}
}
return true;
}
static boolean isPrime(biginger n){
BigInteger二=BigInteger.ONE.add(BigInteger.ONE);
if(n.mod(2).equals(BigInteger.ZERO)){
返回false;
}
biginger h=2.add(biginger.ONE);
//对于(;h*h
我认为使用此方法检查10^128+7
是否为prime需要很长时间。这是一个1后面有128个零的数字。顺便问一下,你有什么问题?你刚才描述了你想做什么,而不是你的问题;这要花很长时间。而是使用biginger.isProbablePrime
方法。