Skip to content

Commit da71276

Browse files
committed
feat: implement Pollard's Rho algorithm for integer factorization
1 parent 6eb1756 commit da71276

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Maths/PollardsRho.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Pollard’s Rho Algorithm for Integer Factorization
3+
*
4+
* Pollard’s Rho is a probabilistic algorithm for integer factorization, especially effective for large composite numbers.
5+
* Reference: https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm
6+
*/
7+
8+
function gcd(a, b) {
9+
while (b !== 0) {
10+
[a, b] = [b, a % b]
11+
}
12+
return a
13+
}
14+
15+
/**
16+
* Returns a non-trivial factor of n, or n if n is prime
17+
* @param {number} n - Integer to factor
18+
* @returns {number} - A non-trivial factor of n
19+
*/
20+
export function pollardsRho(n) {
21+
if (n % 2 === 0) return 2
22+
let x = 2, y = 2, d = 1, f = v => (v * v + 1) % n
23+
while (d === 1) {
24+
x = f(x)
25+
y = f(f(y))
26+
d = gcd(Math.abs(x - y), n)
27+
}
28+
return d === n ? n : d
29+
}
30+
31+
// Example usage:
32+
// const n = 8051;
33+
// console.log(pollardsRho(n)); // Output: a non-trivial factor of 8051

0 commit comments

Comments
 (0)