MBE_factorization_method.pl 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/perl
  2. # Author: Trizen
  3. # Date: 12 March 2022
  4. # https://github.com/trizen
  5. # A new integer factorization method, using the binary exponentiation algorithm with modular exponentiation.
  6. # We call it the "Modular Binary Exponentiation" (MBE) factorization method.
  7. # Similar in flavor to the Pollard's p-1 method.
  8. # See also:
  9. # https://en.wikipedia.org/wiki/Exponentiation_by_squaring
  10. use 5.020;
  11. use strict;
  12. use warnings;
  13. use experimental qw(signatures);
  14. use Math::GMPz;
  15. sub MBE_factor ($n, $max_k = 1000) {
  16. if (ref($n) ne 'Math::GMPz') {
  17. $n = Math::GMPz->new("$n");
  18. }
  19. my $t = Math::GMPz::Rmpz_init();
  20. my $g = Math::GMPz::Rmpz_init();
  21. my $a = Math::GMPz::Rmpz_init();
  22. my $b = Math::GMPz::Rmpz_init();
  23. my $c = Math::GMPz::Rmpz_init();
  24. foreach my $k (1 .. $max_k) {
  25. #say "Trying k = $k";
  26. Math::GMPz::Rmpz_div_ui($t, $n, $k + 1);
  27. Math::GMPz::Rmpz_set($a, $t);
  28. Math::GMPz::Rmpz_set($b, $t);
  29. Math::GMPz::Rmpz_set_ui($c, 1);
  30. foreach my $i (0 .. Math::GMPz::Rmpz_sizeinbase($b, 2) - 1) {
  31. if (Math::GMPz::Rmpz_tstbit($b, $i)) {
  32. Math::GMPz::Rmpz_powm($c, $a, $c, $n);
  33. Math::GMPz::Rmpz_sub_ui($g, $c, 1);
  34. Math::GMPz::Rmpz_gcd($g, $g, $n);
  35. if (Math::GMPz::Rmpz_cmp_ui($g, 1) > 0 and Math::GMPz::Rmpz_cmp($g, $n) < 0) {
  36. return $g;
  37. }
  38. }
  39. Math::GMPz::Rmpz_powm($a, $a, $a, $n);
  40. }
  41. }
  42. return;
  43. }
  44. say MBE_factor("3034271543203"); #=> 604727
  45. say MBE_factor("43120971427631"); #=> 5501281
  46. say MBE_factor("1548517437362569"); #=> 24970961
  47. say MBE_factor("18446744073709551617"); #=> 274177
  48. say MBE_factor("5889680315647781787273935275179391"); #=> 133337
  49. say MBE_factor("25246363781991463940137062180162737"); #=> 6156182033
  50. say MBE_factor("133337481996728163387583397826265769"); #=> 401417
  51. say MBE_factor("950928942549203243363840778331691788194718753"); #=> 340282366920938463463374607431768211457