Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Added Miller Rabin Primality test#1748

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
Amal-Verma wants to merge4 commits intoTheAlgorithms:master
base:master
Choose a base branch
Loading
fromAmal-Verma:feat/added-miller-rabin-primality-test
Open
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletionsMaths/MillerRabin.js
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
/**
* @function millerRabin
* @description Check if number is prime or not (accurate for 64-bit integers)
* @param {Integer} n
* @returns {Boolean} true if prime, false otherwise
* @url https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
* note: Here we are using BigInt to handle large numbers
**/

// Modular Binary Exponentiation (Iterative)
const binaryExponentiation = (base, exp, mod) => {
base = BigInt(base)
exp = BigInt(exp)
mod = BigInt(mod)

let result = BigInt(1)
base %= mod
while (exp) {
if (exp & 1n) {
result = (result * base) % mod
}
base = (base * base) % mod
exp = exp >> 1n
}
return result
}

// Check if number is composite
const checkComposite = (n, a, d, s) => {
let x = binaryExponentiation(a, d, n)
if (x == 1n || x == n - 1n) {
return false
}

for (let r = 1; r < s; r++) {
x = (x * x) % n
if (x == n - 1n) {
return false
}
}
return true
}

// Miller Rabin Primality Test
export const millerRabin = (n) => {
n = BigInt(n)

if (n < 2) {
return false
}

let s = 0n
let d = n - 1n
while ((d & 1n) == 0) {
d = d >> 1n
s++
}

// Only first 12 primes are needed to be check to find primality of any 64-bit integer
let prime = [2n, 3n, 5n, 7n, 11n, 13n, 17n, 19n, 23n, 29n, 31n, 37n]
for (let a of prime) {
if (n == a) {
return true
}
if (checkComposite(n, a, d, s)) {
return false
}
}
return true
}

[8]ページ先頭

©2009-2025 Movatter.jp