Guest User

Extended Euclidean algorithm

a guest
Feb 8th, 2012
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scheme 0.65 KB | None | 0 0
  1. ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2. ;; Extended Euclidean algorithm
  3. ;; finds gcd(a,b) and solves ax+by=gcd(a,b)
  4. ;; returns 3 values: gcd(a,b) x y
  5. ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  6. (define (egcd a b)
  7.   (let loop ([a a] [b b] [x 0] [y 1] [last-x 1] [last-y 0])
  8.     (if (zero? b)
  9.     (values a last-x last-y)    ; result
  10.     (let ([q (quotient a b)])
  11.       (loop b           ; a
  12.         (remainder a b)     ; b
  13.         (- last-x (* q x))  ; x
  14.         (- last-y (* q y))  ; y
  15.         x               ; last-x
  16.         y)))))                  ; last-y
  17.  
  18. (define (test-egcd a b)
  19.   (let-values ([(g x y) (egcd a b)])
  20.     (printf "g=~a x=~a y=~a ax+by=~a" g x y (+ (* a x)
  21.                            (* b y)))))
Advertisement
Add Comment
Please, Sign In to add comment