pollard_rho_factorization.sf 678 B

123456789101112131415161718192021222324252627282930313233
  1. #!/usr/bin/ruby
  2. # Pollard's rho integer factorization algorithm.
  3. # See also:
  4. # https://facthacks.cr.yp.to/rho.html
  5. # https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm
  6. func rho_factor(n, tries = 50000) {
  7. func f(x) { # can be any polynomial
  8. powmod(x, 2, n) + 1
  9. }
  10. var x = f(1)
  11. var y = f(x)
  12. tries.times {
  13. x = f(x)
  14. y = f(f(y))
  15. is_coprime(n, x-y) || break
  16. }
  17. return gcd(x-y, n)
  18. }
  19. say rho_factor(503*863) #=> 863
  20. say rho_factor(33670570905491953) #=> 36169843
  21. say rho_factor(314159265358979323) #=> 317213509
  22. say rho_factor(242363923520394591022973) #=> 786757556719