Skip to content

Instantly share code, notes, and snippets.

@WalterInSH
Created February 20, 2014 05:48
Show Gist options
  • Save WalterInSH/9107694 to your computer and use it in GitHub Desktop.
Save WalterInSH/9107694 to your computer and use it in GitHub Desktop.
Miller Rabin primality test
private boolean passesMillerRabin(int iterations, Random rnd) {
// Find a and m such that m is odd and this == 1 + 2**a * m
BigInteger thisMinusOne = this.subtract(ONE);
BigInteger m = thisMinusOne;
int a = m.getLowestSetBit();
m = m.shiftRight(a);
// Do the tests
if (rnd == null) {
rnd = getSecureRandom();
}
for (int i=0; i<iterations; i++) {
// Generate a uniform random on (1, this)
BigInteger b;
do {
b = new BigInteger(this.bitLength(), rnd);
} while (b.compareTo(ONE) <= 0 || b.compareTo(this) >= 0);
int j = 0;
BigInteger z = b.modPow(m, this);
while(!((j==0 && z.equals(ONE)) || z.equals(thisMinusOne))) {
if (j>0 && z.equals(ONE) || ++j==a)
return false;
z = z.modPow(TWO, this);
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment