Project Euler in Clojure – Problem 6

In trying to learn Clojure and wrap my head around good functional programming, and hoping to learn more idiomatic Clojure, I have started working through the Project Euler problems. In doing this, I have also setup a repository on github.com to keep track of my progress, which can be found at https://github.com/stevenproctor/project-euler-clojure.  My approach to Problem 5 can be found here.

Problem 6 of Project Euler is described as:

Find the difference between the sum of the squares of the
first one hundred natural numbers and the square of the sum.

This is another problem that seems to translate almost directly from the problem statement into the operations that need to be performed.

I find the square of the sums from 1 to the (inc n), where n is bound to 100 for the problem definition, as I want the number that n is bound to to be included in the range. This is coded as:

(Math/pow (reduce + (range 1 (inc n))) 2)

As well as I find the sum of the squares from 1 to the (inc n).

(reduce + (map #(Math/pow % 2) (range 1 (inc n))))

I then pieced these two solutions together, subtracting the two values. When doing this at the REPL, it gave the result as an exponent, which I didn’t like the look of, so I put the function bigint around the subtraction function, giving the full solution as:

(defn problem6
  ([] (problem6 100))
  ([n] (bigint (-
         (Math/pow (reduce + (range 1 (inc n))) 2)
         (reduce + (map #(Math/pow % 2) (range 1 (inc n))))))))

Again, I would love comments and suggestions on my solution to this problem, and if there are tweaks to make it more Clojure-ish.

**Update**
My solution to Problem 7 can be found here.

–Proctor

Advertisements

, ,

  1. #1 by Arcane Sentiment on June 7, 2012 - 19:49

    Don’t hesitate to make convenience functions. If you want to express the problem in terms of square and sum, then define them — they’re easy and they let you avoid writing (Math/pow ... 2) and (reduce + ...) repeatedly.

    If you use * instead of Math/pow, you can avoid converting to floats.

    • #2 by Proctor on June 7, 2012 - 20:42

      Thanks for the tips. I will have to keep this in mind, and think about refactoring more as well as I try and learn Clojure.

  1. Project Euler in Clojure – Problem 5 « Proctor It
  2. Project Euler in Clojure – Problem 7 « Proctor It

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: