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.
Sieve of Atkin speeds up (asymptotically) the process of generating prime numbers. However, it is more complicated than the others. Comparing this running time with the previous ones shows that the sieve of Atkin is the fastest algorithm for generating prime numbers.
isProbablePrime(int certainty): A method in BigInteger class to check if a given number is prime. For certainty = 1, it return true if BigInteger is prime and false if BigInteger is composite.
In mathematics, the sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit.
Time Complexity: O(sqrt n) because recursive function will call itself at most sqrt(n) times.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With