From the archive

The First Problem I Solved Using Clojure

Spoiler Alert! Problem one from Project Euler explained.

This week I am working on solving problems from Project Euler using Clojure. The first problem is this...

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

The first thing I did was read through the problem and break it into a rough draft of small part in some kind of procedure order. It looked like this...

```clojure for 3 ;inc * n 3 ? # < 1000 cond- yes- into list no - break loop add to list same for 5 add two lists ```

I then went back to the koans to look for patterns that I was trying to create. I then also looked at the docs for methods that I thought I would want to use. After that, things were looking and feeling too complicated and I decided to come up with a new plan. It looked like this...

```clojure new plan -> range up to 1000 inclusive take the #, divide by (3 or 5) if there is no remainder, add to multiples list, do the next number need to put this in a list or set(filter multiple-of-three (range 1000)) need to put this in a list or set(filter multiple-of-five (range 1000)) then ```

By the time I got to the last line of that plan, I had a new plan...

```clojure new new plan -> find multiples of 2 numbers (it can take 2 args we will give 3 and 5) then we will have a range 1000 if multiple of n put into list if mult of f put into list add up #s in list. ```

Alright, So I started with a test...

```clojure (it "should return the number if the passed in number is a multiple of the second passed in number" (should= 10 (multiple-of-number 10 5))) ;and the function (defn multiple-of-number [number multiple-candidate] (if (true? (= 0 (rem number multiple-candidate))) number)) ```

And the next test...

```clojure (it "should be able add up a list of multiples" (should= 1997 (sum-of-the-multiples 999 998))) ;and the method. (defn sum-of-the-multiples [number1 number2] (reduce + (filter (fn [index] (or (multiple-of-number index number1) (multiple-of-number index number2))) (range 1 1000)))) ```

That little guy packs a big punch! Now I ended up getting the final number by passing 3 and 5 into my test as the arguments and then passing the wrong number as the argument to should. Now that I am writing this, I should really change this function to print out the answer. Let's make it better.

```clojure (it "should be able add up a list of multiples" (should= "233168" (sum-of-the-multiples 3 5))) ;and the soloution (defn sum-of-the-multiples [number1 number2] (pr-str (reduce + (filter (fn [index] (or (multiple-of-number index number1) (multiple-of-number index number2))) (range 1 1000))))) ```

Sweet refactor! :)