Project Euler Problem 9

Ivar Thorson bio photo By Ivar Thorson

Brute force! Side effects! Square roots!? What have I done?! Functional Puritans out there, you may want to shield your children’s eyes!

What follows is the kind of clojure code you write to solve problem 9 if you spend all day coding in C:

(defn euler-9 [sum]
   (for [a (range 1 sum)
         b (range 1 sum)]
     (let [c (int (Math/sqrt (+ (* a a) (* b b))))]
       (when (and (= sum (+ a b c))
                  (= (* c c)  (+ (* a a) (* b b))))
         (printf "a=%d, b=%d, c=%d\n" a b c)))))

(euler-9 1000)

The nil at the end ensures we discard the unneeded return values without returning them to the repl. Multiply the three numbers that were printed together, and you are done!

“But surely…” you cry, “…there must be a better way!” Well, the venerable Chris Houser has posted a much better solution… Here is his solution, given a name:

;; Thanks chouser!
(defn euler-9b [sum]
  (for [a (range 1 sum)
        b (range a sum)
        c [(- sum a b)]
        :when (= (+ (* a a) (* b b)) (* c c))]
    (bigint (* a b c))))

(euler-9b 1000)

Lesson of the day: It’s easy to forget how powerful for is!