in Programming

Project Euler Problem 6 Solution: Clojure

Problem description, from Project Euler

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

Solution

This one actually seemed to be easier than the others. No filters required!

1
2
3
4
5
6
7
8
9
(defn problem06
    [upper]
    (defn sq [n] (* n n))
    (def l (range 1 (+ upper 1)))
    (-
        (sq (reduce + l))
        (reduce + (map sq l))
        )
    )

The biggest hangup I had was that when I originally read the problem, I thought I’d need a power function, and then spent at least 15 minutes determining there was no Clojure core power function. I found some alternatives here:

1
2
3
4
; for integers (cuz it's faster)
(. (. java.math.BigInteger (valueOf 2)) (pow 5))
; for doubles
(. java.lang.Math (pow 2 -3))

Comments are closed.