I wrote two methods to test wheter a BigInteger is a prime or not. I start with (2^64)+1 and then I always add 2 until I find a prime. These are the two methods:
public static boolean isPrime(BigInteger n) {
BigInteger max_long = BigInteger.valueOf(Long.MAX_VALUE);
if (n.compareTo(max_long)<=0) return isPrime(n.longValue());
final BigInteger two = new BigInteger ("2");
if ((n.mod(two)).compareTo(BigInteger.ZERO)==0) return false;
else {
for (BigInteger i=new BigInteger ("3"); i.multiply(i).compareTo(n)<=0; i=i.add(two)) {
if((n.mod(i)).compareTo(BigInteger.ZERO)==0) return false;
}
}
return true;
}
The other one is:
public static boolean isPrimeImproved (BigInteger n) {
BigInteger max_long = BigInteger.valueOf(Long.MAX_VALUE);
if(n.compareTo(max_long)<=0) return isPrime(n.longValue());
final BigInteger two = new BigInteger("2");
if(n.mod(two).compareTo(BigInteger.ZERO)==0) return false;
else {
for(BigInteger i=new BigInteger("3"); i.multiply(i).compareTo(n)<=0; i=i.nextProbablePrime()) {
if(n.mod(i).compareTo(BigInteger.ZERO)==0) return false;
}
}
return true;
}
The first one terminates after around 310 seconds. But the second one doesn't seem to terminate, although it should be faster, shouldn't it? And I know, that there is a method called isProbablePrime(), but I mustn't use it.