Skip to content

Instantly share code, notes, and snippets.

@rvighne
Created November 12, 2014 00:41
Show Gist options
  • Save rvighne/4c80fe8be73c13866c5d to your computer and use it in GitHub Desktop.
Save rvighne/4c80fe8be73c13866c5d to your computer and use it in GitHub Desktop.
Miller-Rabin probabillistic primality test. You can trade off speed for more accuracy by raising the k argument.
function probablyPrime(n, k) {
// Always prime
if (n === 2 || n === 3)
return true;
// Never prime
if (n % 2 === 0 || n < 2)
return false;
// Write (n - 1) as 2^s * d
var s = 0, d = n - 1;
while (d % 2 === 0) {
d /= 2;
++s;
}
WitnessLoop: do {
// A base between 2 and n - 2
var x = Math.pow(2 + Math.floor(Math.random() * (n - 3)), d) % n;
if (x === 1 || x === n - 1)
continue;
for (var i = s - 1; i--;) {
x = x * x % n;
if (x === 1)
return false;
if (x === n - 1)
continue WitnessLoop;
}
return false;
} while (--k);
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment