Skip to content

Instantly share code, notes, and snippets.

@pete
Created March 5, 2009 01:57
Show Gist options
  • Save pete/74135 to your computer and use it in GitHub Desktop.
Save pete/74135 to your computer and use it in GitHub Desktop.
(frdef gcd ()
; gcd's identity:
() 0
((int? a)) (abs a)
; Make sure that they're sorted ascending
(((curry both int? (curry ! <=)) *l)) (apply gcd (sort l))
; Trivial case:
(a 0) (abs a) ; As making it here means a is negative.
(0 a) a
; If there are more than two args, reduce:
(a b (true *rest (1 -1))) (apply gcd (cons (gcd a b) rest))
; Handle negatives
(((curry both int? (curry > 0)) a) b) (gcd (abs a) b)
; Oh, the actual math should probably happen somewhere. Here's good.
(a b) (gcd (% b a) a))
(frdef lcm ()
() 1
a (abs a)
(a b) (/ (* a b) (gcd a b))
(a b *rest) (apply lcm (cons (lcm a b) rest)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment