After PhillyETE, I wanted to try out some Clojure, so I decided to solve the first problem of Project Euler. I coded up my own solution using some of the references on the Clojure site.
Project Euler Problem Description, from Project Euler
Find the sum of all the multiples of 3 or 5 below N. (N is 1000 is this Project Euler problem.)
My first attempt
(def nmbrs (range 0 1000)) (def multiples (filter #(and (not= % 0) (or (= (rem % 3) 0 ) (= (rem % 5) 0 ) ) ) nmbrs ) ) (reduce + multiples)
Another attempt by a different author
Afterwards, I came across a terser, more elegant solution on a site that seems to have had the same idea as I did, Learning Clojure with Project Euler. The site had a really elegant looking solution:
; //grok-code.com/367/learning-clojure-with-project-euler/ (defn problem01 [limit] (reduce + (filter #(or (zero? (mod % 3)) (zero? (mod % 5))) (take (- limit 1) (iterate inc 1))))) (problem 1000)
My revised attempt
The use of take and iterate are really interesting. I haven’t encountered these “lazy” functions, and was surprised when I tried to run (iterate inc 1) in the REPL. I decided to modify my version with some of the things I learned from the version above, and make it more terse.
(defn problem01 [upper] (reduce + (filter #(or (zero?(rem % 3)) (zero?(rem % 5)) ) (range 1 upper) )) )
I’ll be working on some more of the problems in the coming days.
(PS. If you are wondering why I use rem instead of mod, it’s because I am using an older version of clojure with TextMate–I’ve yet to upgrade)
New blog post: Project Euler Problem 1 Solutio… /programming/project-euler-problem-1-solution-clojure/
This comment was originally posted on Twitter
If you install Homebrew (//mxcl.github.com/homebrew/), installing Clojure is as easy as:
brew install clojure
Cool, I will keep that in mind. I am currently using a clojure version that came with a TextMate bundle. Unfortunately, there are no instructions to upgrade. I’m going to keep trying though.