Discussion On
Learning Clojure with Project Euler

by in Programming Languages

8 Comments

  1. Shane
    Tuesday, September 2213, 2009

    Just an FYI, range returns a lazy seq of nums from start (inclusive) to end (exclusive).
    So (range 1 1000) will return 1 – 999. You don’t need to do (- limit 1).

    Reply
  2. Jess Johnson
    Tuesday, September 2212, 2009

    @Shane Wooops. Thanks for the correction. I’ve updated the code.

    Reply
  3. Patrick Logan
    Tuesday, September 2205, 2009

    Another solution for #1…

    (reduce + (into #{} (concat (range 3 1000 3) (range 5 1000 5))))

    Reply
  4. Alen
    Tuesday, September 2231, 2009

    Problem 2

    #(zero? (mod % 2))

    How about more elegant

    #(even? %)

    There is also companion odd? predicate.

    -Alen

    Reply
  5. Patrick Logan
    Tuesday, September 2247, 2009

    without the concat…

    (reduce + (into (into #{} (range 3 1000 3)) (range 5 1000 5)))

    Reply
  6. Alen
    Thursday, September 2457, 2009

    @jess

    Your solution to the problem 3 looks pretty good. If I may make a suggestion though.
    Instead of doing self-recursion by calling the function directly, use the more efficient self-recursion using the loop / recur combination. Direct self-recursion on function will blow the stack on larger numbers.

    Here are the changes to your version:


    (defn factor [num]
    (loop [n num cur 2]
    (if (= n cur)
    n
    (if (zero? (mod n cur))
    (recur (/ n cur) cur)
    (recur n (inc cur))))))

    Also note how I moved the “cur” from function parameter to loop bindings.

    Oh and by the way, loop/recur is far more efficient.

    Old ver:
    “Elapsed time: 21.654 msecs”

    New ver with loop/recur:
    “Elapsed time: 3.302 msecs”

    -Al

    Reply
  7. Programming Praxis
    Friday, October 201, 2009

    You might also enjoy the programming exercises on my website Programming Praxis.

    Reply
  8. klang
    Tuesday, October 1907, 2010

    With the following small changes, the code runs even faster:


    (defn factor [num]
    (loop [n num cur 2]
    (if (= n cur)
    n
    (if (zero? (rem n cur))
    (recur (quot n cur) cur)
    (recur n (inc cur))))))

    Reply

Leave a Reply