1
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
- **/
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
9
10
10
// Modular Binary Exponentiation (Iterative)
11
11
const binaryExponentiation = ( base , exp , mod ) => {
@@ -15,8 +15,8 @@ const binaryExponentiation = (base, exp, mod) => {
15
15
16
16
let result = BigInt ( 1 )
17
17
base %= mod
18
- while ( exp ) {
19
- if ( exp & 1n ) {
18
+ while ( exp ) {
19
+ if ( exp & 1n ) {
20
20
result = ( result * base ) % mod
21
21
}
22
22
base = ( base * base ) % mod
@@ -28,13 +28,13 @@ const binaryExponentiation = (base, exp, mod) => {
28
28
// Check if number is composite
29
29
const checkComposite = ( n , a , d , s ) => {
30
30
let x = binaryExponentiation ( a , d , n )
31
- if ( x == 1n || x == ( n - 1n ) ) {
31
+ if ( x == 1n || x == n - 1n ) {
32
32
return false
33
33
}
34
34
35
- for ( let r = 1 ; r < s ; r ++ ) {
35
+ for ( let r = 1 ; r < s ; r ++ ) {
36
36
x = ( x * x ) % n
37
- if ( x == n - 1n ) {
37
+ if ( x == n - 1n ) {
38
38
return false
39
39
}
40
40
}
@@ -45,26 +45,26 @@ const checkComposite = (n, a, d, s) => {
45
45
export const millerRabin = ( n ) => {
46
46
n = BigInt ( n )
47
47
48
- if ( n < 2 ) {
48
+ if ( n < 2 ) {
49
49
return false
50
50
}
51
51
52
52
let s = 0n
53
53
let d = n - 1n
54
- while ( ( d & 1n ) == 0 ) {
54
+ while ( ( d & 1n ) == 0 ) {
55
55
d = d >> 1n
56
- s ++ ;
56
+ s ++
57
57
}
58
58
59
59
// Only first 12 primes are needed to be check to find primality of any 64-bit integer
60
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 ) {
61
+ for ( let a of prime ) {
62
+ if ( n == a ) {
63
63
return true
64
64
}
65
- if ( checkComposite ( n , a , d , s ) ) {
65
+ if ( checkComposite ( n , a , d , s ) ) {
66
66
return false
67
67
}
68
68
}
69
- return true ;
69
+ return true
70
70
}
0 commit comments