Java: (slightly advanced) Optimized Fermat Primality Test
Wednesday, 14. June 2006, 20:31:20
This little class enables you to use Fermat's Little Theorem, to check if a number is a (probable) prime or not. Probable because not all positive answers from Fermat's Little Theorem will actually be prime. Those "Carmichael numbers" are pretty rare though, Fermat Primality Test is actually used in the notorious PGP encryption software. Optimized because it uses a much faster algorithm for calculating the modular exponentiation.
You will need to import these packages:
ATT: You have to seed your random generator only once
Here is the main class:
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:
Update:
With a some friendly help from 'YAT_Archivist' over at the Sun Java Forums, I've improved the code.
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.







