问题
I am writing a method that detects if a BigInteger is prime or not. I have used the following code/algorithm to check if a given number is prime or not. But this is extremely slow and takes long time if a number is lets say 10 digits long.
public boolean returnPrime(BigInteger testNumber){
int divisorCounter=1;
BigInteger index,i ;
for ( index= new BigInteger("2"); index.compareTo(testNumber) !=1; index=index.add(new BigInteger("1"))){
System.out.println(index);
for(i= new BigInteger("2"); i.compareTo(index) != 1; i=i.add(new BigInteger("1"))){
if((testNumber.mod(i).equals(BigInteger.ZERO) )){
divisorCounter++;
}
if(divisorCounter>2){
return false;
}
}
}
return true;
}
Is there any better algorithms to work with BigInteger prime number? I could not find a question related to this in Stackoverflow. If you have came across such question please let me know or if you have an idea on how to solve then your ideas are much appreciated.
回答1:
Here's an optimized version using testing only up to sqrt(n) and using the Miller-Rabin test (as of Joni's answer):
public boolean returnPrime(BigInteger number) {
//check via BigInteger.isProbablePrime(certainty)
if (!number.isProbablePrime(5))
return false;
//check if even
BigInteger two = new BigInteger("2");
if (!two.equals(number) && BigInteger.ZERO.equals(number.mod(two)))
return false;
//find divisor if any from 3 to 'number'
for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(number) < 1; i = i.add(two)) { //start from 3, 5, etc. the odd number, and look for a divisor if any
if (BigInteger.ZERO.equals(number.mod(i))) //check if 'i' is divisor of 'number'
return false;
}
return true;
}
回答2:
Check if the integer is a "probable prime." If it's not you know for sure that it's composite and you avoid the slow factorization.
if (!testNumber.isProbablePrime(5)) return false;
Also you only need to make trial divisions only up to the square root of testNumber
. If K is composite you know that its least prime factor must be at most sqrt(K).
回答3:
Some other simple improvements would be to limit your set of possible numbers to only two and odd numbers in your outer loop and also to only iterate up to the square root of "index" (or index / 2 if too hard to calculate) in your inner loop.
来源:https://stackoverflow.com/questions/32035259/fastest-algorithm-to-find-if-a-biginteger-is-a-prime-number-or-not