Java: (slightly advanced) Optimized Fermat Primality Test
Wednesday, June 14, 2006 8:31:20 PM
You will need to import these packages:
import java.math.BigInteger; import java.util.Random;
ATT: You have to seed your random generator only once
Random generator = new Random();
Here is the main class:
class FermatPrime {
public static boolean doTest (BigInteger p, int prob) {
for (int c = 0; c < prob; c++) {
if(!doModPow(p)) {
return false;
}
}
return true;
}
public static boolean doModPow (BigInteger n) {
long rndnum = 1 + generator.nextInt(99);
BigInteger b = BigInteger.valueOf(rndnum);
return b.modPow((n.subtract(n.ONE)), n).equals(n.ONE);
}
}
The doTest method takes two arguments. The first argument is the actually number you want to test for primality. The second argument is how many times you want to run the primality test, in otherwords how much certainty you want.
Example usage:
if (FermatPrime.doTest(BigInteger.valueOf(101L), 5)) {
System.out.println("We got ourselves a probable prime! :)");
} else {
System.out.println("Doh, not a prime! :(");
}
Update:
With a some friendly help from 'YAT_Archivist' over at the Sun Java Forums, I've improved the code.







