On Thu, Feb 17, 2011 at 12:34 AM, HB <[email protected]> wrote:
> I'm trying to write a function that determines if a number is a prime
> or not.
> Here is my first shot:
>
> (defn prime? [num]
> (loop [i 2]
> (if (<= (* i i) num)
> false)
> (recur (inc i)))
> true)
>
> It is not working to be sure :)
>
> Please blow my mind with various implementations.
It seems that you're mixing loop expression in Clojure with a Java
loop. The loop in Clojure is just a binding and a point to which each
recur will jump, instead of the start of function. You're lacking a
stop condition in the loop.
Here is the solution similiar to yours, but with a proper accumulator
and stop condition:
(defn prime? [n]
(let [m (Math/sqrt n))]
(loop [k 2]
(cond
(> k m) true
(zero? (mod n k)) false
true (recur (inc k))))))
IMHO more idiomatic Clojure solution, using seq operations:
(defn prime? [n]
(if (< n 2)
false
(not-any? #(zero? (rem n %))
(range 2 (min (inc (Math/sqrt n)) n)))))
Cheers,
--
Marek Stępniowski
http://stepniowski.com
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en