Skip to content

Instantly share code, notes, and snippets.

@pasali
Created December 21, 2013 00:15
Show Gist options
  • Save pasali/8063647 to your computer and use it in GitHub Desktop.
Save pasali/8063647 to your computer and use it in GitHub Desktop.
import java.math.BigInteger;
import java.util.Random;
public class MillerRabin {
public static final BigInteger ZERO = BigInteger.ZERO;
public static final BigInteger ONE = BigInteger.ONE;
public static final BigInteger TWO = BigInteger.valueOf(2);
public static final int[] aValues = { 2, 3 };
public static boolean testPr(BigInteger n, BigInteger a, int s, BigInteger d) {
for (int i = 0; i < s; i++) {
BigInteger exp = TWO.pow(i);
exp = exp.multiply(d);
BigInteger res = a.modPow(exp, n);
if (res.equals(n.subtract(ONE)) || res.equals(ONE)) {
return true;
}
}
return false;
}
public static boolean millerRabin(BigInteger n, int numValues) {
BigInteger d = n.subtract(ONE);
int s = 0;
while (d.mod(TWO).equals(ZERO)) {
s++;
d = d.divide(TWO);
}
for (int i = 0; i < numValues; i++) {
BigInteger a = BigInteger.valueOf(aValues[i]);
boolean r = testPr(n, a, s, d);
if (!r) {
return false;
}
}
return true;
}
public static void main(String[] args) {
BigInteger p = new BigInteger(1024, new Random());
while (millerRabin(p, aValues.length) == false) {
p = p.add(TWO);
}
System.out.println(p);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment