Skip to content

Instantly share code, notes, and snippets.

@zaneli
Created February 24, 2015 13:21
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 zaneli/bec9f2e9a074fe079a2c to your computer and use it in GitHub Desktop.
Save zaneli/bec9f2e9a074fe079a2c to your computer and use it in GitHub Desktop.
「ClojureでNinety-Nine Lisp Problems(P31~33)」ブログ用
(defn my-prime?
"Determine whether a given integer number is prime."
([n]
(cond
(<= n 1) false
(== n 2) true
(== (rem n 2) 0) false
(some #(== (rem n %) 0) (range 3 (inc (Math/sqrt n)) 2)) false
:else true)))
(defn my-gcd
"Determine the greatest common divisor of two positive integer numbers."
[n m]
(cond
(== n 0) m
(neg? n) (my-gcd (- n) m)
(neg? m) (- (my-gcd n (- m)))
:else (my-gcd (rem m n) n)))
(defn my-gcd
"Determine the greatest common divisor of two positive integer numbers."
[n m]
(cond
(== n 0) (Math/abs m)
(== m 0) (Math/abs n)
:else (let [ns (range (quot (max (Math/abs n) (Math/abs m)) 2) 0 -1)]
(some #(if (and (== (rem n %) 0) (== (rem m %) 0)) %) ns))))
(declare my-gcd)
(defn my-coprime?
"Determine whether two positive integer numbers are coprime."
[n m]
(let [g (my-gcd n m)] (or (== g 1) (== g -1))))
(defn my-gcd
"Determine the greatest common divisor of two positive integer numbers."
[n m]
(cond
(== n 0) m
(neg? n) (my-gcd (- n) m)
(neg? m) (- (my-gcd n (- m)))
:else (my-gcd (rem m n) n)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment