modular_exponentiation.rb 534 B

123456789101112131415161718192021222324252627282930313233
  1. #!/usr/bin/ruby
  2. # Modular exponentation (by squaring) algorithm.
  3. # See also:
  4. # https://en.wikipedia.org/wiki/Modular_exponentiation
  5. def expmod(a, b, n)
  6. c = 1
  7. while (true)
  8. if (b.odd?)
  9. c *= a
  10. c %= n
  11. end
  12. a *= a
  13. a %= n
  14. b >>= 1
  15. break if b.zero?
  16. end
  17. return c
  18. end
  19. puts expmod(
  20. 2988348162058574136915891421498819466320163312926952423791023078876139,
  21. 2351399303373464486466122544523690094744975233415544072992656881240319,
  22. 10**40
  23. )