pollard_rho_factorization.pl 888 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/perl
  2. # Simple implementation of 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. use 5.020;
  7. use strict;
  8. use warnings;
  9. use experimental qw(signatures);
  10. use Math::AnyNum qw(:overload powmod gcd);
  11. sub rho_factor ($n, $tries = 50000) {
  12. my sub f($x) {
  13. powmod($x, 2, $n) + 1;
  14. }
  15. my $x = f(2);
  16. my $y = f($x);
  17. for (1 .. $tries) {
  18. $x = f($x);
  19. $y = f(f($y));
  20. my $g = gcd($x - $y, $n);
  21. $g <= 1 and next;
  22. $g >= $n and last;
  23. return $g;
  24. }
  25. return 1;
  26. }
  27. say rho_factor(503 * 863); #=> 863
  28. say rho_factor(33670570905491953); #=> 36169843
  29. say rho_factor(314159265358979323); #=> 317213509
  30. say rho_factor(242363923520394591022973); #=> 786757556719