chinese_remainder_theorem.sf 519 B

123456789101112131415161718192021222324252627282930313233
  1. #!/usr/bin/ruby
  2. # Simple implementation of the Chinese Remainder Theorem (CRT) for solving x in:
  3. #
  4. # x = a_1 (mod n_1)
  5. # x = a_2 (mod n_2)
  6. # ...
  7. # x = a_k (mod n_k)
  8. #
  9. func CRT (*congruences) {
  10. var c = 0
  11. var m = congruences.lcm { _[1] }
  12. for a,n in (congruences) {
  13. var t = m/n
  14. var u = (t * invmod(t, n))
  15. c += ((a*u) % m)
  16. }
  17. return (c % m)
  18. }
  19. # Example for:
  20. # x = 2 (mod 3)
  21. # x = 3 (mod 5)
  22. # x = 2 (mod 7)
  23. say CRT([2, 3], [3, 5], [2, 7]) #=> 23