extended_greatest_common_divisor.sf 745 B

123456789101112131415161718192021222324252627282930313233343536
  1. #!/usr/bin/ruby
  2. # Algorithm for computing the extended greatest common divisor of two integers.
  3. # Algorithm presented in the book:
  4. #
  5. # Modern Computer Arithmetic
  6. # - by Richard P. Brent and Paul Zimmermann
  7. #
  8. func extended_gcd(a, b) {
  9. var (u, w) = (1, 0)
  10. var (v, x) = (0, 1)
  11. var (q, r) = (0, 0)
  12. while (b != 0) {
  13. (q, r) = divmod(a, b)
  14. (a, b) = (b, r)
  15. (u, w) = (w, u - q*w)
  16. (v, x) = (x, v - q*x)
  17. }
  18. return (a, u, v)
  19. }
  20. var a = 31738434
  21. var b = 143626392
  22. var (g, u, v) = extended_gcd(a, b)
  23. say "gcd(#{a}, #{b}) = #{g}" #=> gcd(31738434, 143626392) = 546
  24. say "#{u}*#{a} + #{v}*#{b} = #{g}" #=> 55417*31738434 + -12246*143626392 = 546
  25. assert_eq(u*a + v*b, g)