A high-performance TypeScript library for primality testing using Miller-Rabin and Fermat algorithms. Designed with BigInt support for cryptographic-grade calculations.
- Miller-Rabin Test: Robust probabilistic test.
- Fermat Primality Test: Fast probabilistic test based on Fermat's Little Theorem.
- BigInt Support: Test extremely large numbers without precision loss.
- Zero Dependencies: Lightweight and optimized for performance.
pnpm add @marlonwq/primalityimport { isPrimeMillerRabin, isPrimeFermat } from '@marlonwq/primality';
// Using Miller-Rabin (Recommended for high accuracy)
// Use the 'n' suffix for BigInt literals
const num1 = 104729n;
console.log(isPrimeMillerRabin(num1)); // true
// Using Fermat (Faster, but watch out for Carmichael numbers)
const num2 = 561n;
console.log(isPrimeFermat(num2)); // true (Fermat's false positive)
console.log(isPrimeMillerRabin(num2)); // false (Miller-Rabin's correct answer)Click to expand the mathematical background
The Miller-Rabin test is an evolution of Fermat's Little Theorem. Fermat states that if
The Miller-Rabin Secret
The core of Miller-Rabin is the fact that in a prime field
The Algorithm Steps:
- Write
$n - 1$ as$2^s \cdot d$ by repeatedly factoring out powers of 2. - Pick a random base
$a$ in the range$[2, n - 2]$ . - Compute
$x = a^d \pmod n$ . If$x = 1$ or$x = n - 1$ , the number is a probable prime. - Otherwise, square
$x$ repeatedly ($x = x^2 \pmod n$ ) up to$s - 1$ times. - If at any point
$x = n - 1$ , the number is a probable prime. - If the loop finishes without ever hitting
$n - 1$ , the number is definitely composite.
Accuracy
Miller-Rabin is a probabilistic algorithm. Each iteration (
We use pnpm as our package manager. To get started:
pnpm install
pnpm build
pnpm test
If you find this project helpful, please consider contributing in the following ways: Submitting a pull request, opening an issue, giving the project a star or buying me a coffee!!