miller-rabin_factorization_method.sf 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/ruby
  2. # Factorization method, based on the Miller-Rabin primality test.
  3. # Described in the book "Elementary Number Theory", by Peter Hackman.
  4. # Works best on Carmichael numbers.
  5. # Example:
  6. # N = 1729
  7. # N-1 = 2^6 * 27
  8. # Then, we find that:
  9. # 2^(2*27) == 1065 != -1 (mod N)
  10. # and
  11. # 2^(4*27) == 1 (mod N)
  12. # This proves that N is composite and gives the following factorization:
  13. # x = 2^(2*27) (mod N)
  14. # N = gcd(x+1, N) * gcd(x-1, N)
  15. # N = gcd(1065+1, N) * gcd(1065-1, N)
  16. # N = 13 * 133
  17. # See also:
  18. # https://www.math.waikato.ac.nz/~kab/509/bigbook.pdf
  19. # https://en.wikipedia.org/wiki/Miller-Rabin_primality_test
  20. func miller_rabin_factor(n, tries=100) {
  21. var D = n-1
  22. var s = D.valuation(2)
  23. var r = s-1
  24. var d = D>>s
  25. tries.times {
  26. var a = random_prime(1e7)
  27. var x = powmod(a, d, n)
  28. for b in (0..r) {
  29. break if ((x == 1) || (x == D))
  30. for i in (1, -1) {
  31. var g = gcd(x+i, n)
  32. if (g.is_between(2, n-1)) {
  33. return g
  34. }
  35. }
  36. x = powmod(x, 2, n)
  37. }
  38. }
  39. return 1
  40. }
  41. say miller_rabin_factor(1729)
  42. say miller_rabin_factor(335603208601)
  43. say miller_rabin_factor(30459888232201)
  44. say miller_rabin_factor(162021627721801)
  45. say miller_rabin_factor(1372144392322327801)
  46. say miller_rabin_factor(7520940423059310542039581)
  47. say miller_rabin_factor(8325544586081174440728309072452661246289)
  48. say miller_rabin_factor(181490268975016506576033519670430436718066889008242598463521)
  49. say miller_rabin_factor(57981220983721718930050466285761618141354457135475808219583649146881)
  50. say miller_rabin_factor(131754870930495356465893439278330079857810087607720627102926770417203664110488210785830750894645370240615968198960237761)