Skip to content

Commit 7997eec

Browse files
committed
Added Miller Rabin for 64-bit integers
1 parent 55ff0ad commit 7997eec

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

Maths/MillerRabin.js

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/**
2+
* @function millerRabin
3+
* @description Check if number is prime or not (accurate for 64-bit integers)
4+
* @param {Integer} n
5+
* @returns {Boolean} true if prime, false otherwise
6+
* @url https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
7+
* note: Here we are using BigInt to handle large numbers
8+
**/
9+
10+
// Modular Binary Exponentiation (Iterative)
11+
const binaryExponentiation = (base, exp, mod) => {
12+
base = BigInt(base)
13+
exp = BigInt(exp)
14+
mod = BigInt(mod)
15+
16+
let result = BigInt(1)
17+
base %= mod
18+
while(exp){
19+
if (exp & 1n){
20+
result = (result * base) % mod
21+
}
22+
base = (base * base) % mod
23+
exp = exp >> 1n
24+
}
25+
return result
26+
}
27+
28+
// Check if number is composite
29+
const checkComposite = (n, a, d, s) => {
30+
let x = binaryExponentiation(a, d, n)
31+
if (x == 1n || x == (n - 1n)){
32+
return false
33+
}
34+
35+
for (let r = 1; r < s; r++){
36+
x = (x * x) % n
37+
if (x == n - 1n){
38+
return false
39+
}
40+
}
41+
return true
42+
}
43+
44+
// Miller Rabin Primality Test
45+
export const millerRabin = (n) => {
46+
n = BigInt(n)
47+
48+
if (n < 2){
49+
return false
50+
}
51+
52+
let s = 0n
53+
let d = n - 1n
54+
while((d & 1n) == 0){
55+
d = d >> 1n
56+
s++;
57+
}
58+
59+
// Only first 12 primes are needed to be check to find primality of any 64-bit integer
60+
let prime = [2n, 3n, 5n, 7n, 11n, 13n, 17n, 19n, 23n, 29n, 31n, 37n]
61+
for(let a of prime){
62+
if (n == a){
63+
return true
64+
}
65+
if (checkComposite(n, a, d, s)){
66+
return false
67+
}
68+
}
69+
return true;
70+
}

0 commit comments

Comments
 (0)