File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments