Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisvest/953830 to your computer and use it in GitHub Desktop.
Save chrisvest/953830 to your computer and use it in GitHub Desktop.
;; chrisvest's solution to http://4clojure.com/problem/66
;; Using Euclid's algorithm
(fn gcd [a b]
(loop [dividend (max a b)
divisor (min a b)
quotient (quot dividend divisor)
remainder (rem dividend divisor)]
(if (zero? remainder)
divisor
(recur divisor
remainder
(quot divisor remainder)
(rem divisor remainder)))))
@igstan
Copy link

igstan commented May 5, 2011

I just translated Wikipedia's definition of Euclid's algorithm and end up with this:

(fn gcd [a b]
  (if (= b 0) a
    (gcd b (mod a b))))

I guess you went the loop/recur way to avoid a stack overflow, right (which I didn't think about)? So... this seems to do it.

(fn gcd [a b]
  (loop [a a b b]
    (if (zero? b) a
        (recur b (mod a b)))))

@chrisvest
Copy link
Author

Nice!
I translated from another article that tried to explain how the algorithm worked in detail, so I guess it's no wonder that my version ended up over-engineered.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment