solve_linear_congruence_equation.sf 548 B

1234567891011121314151617181920212223242526272829303132
  1. #!/usr/bin/ruby
  2. # Solve a*x = b (mod n)
  3. func solve_lcg (a, b, n) {
  4. var d = gcd(a, n)
  5. # No solution if `d` does not divide `b`
  6. return nil if !(d `divides` b)
  7. a /= d
  8. b /= d
  9. n /= d
  10. var t = invmod(a, n)
  11. var x = ((t*b) % n)
  12. return x
  13. }
  14. func solve_lcg_simple (a, b, n) {
  15. (invmod(a, n) * b) % n
  16. }
  17. var a = 10**5 # coefficient of x
  18. var b = -19541 # congruent to this
  19. var n = 19543 # modulo this number
  20. say solve_lcg(a, b, n) #=> 10785
  21. say solve_lcg_simple(a, b, n) #=> 10785