in Programming

Project Euler Problem 9 Solution: Clojure

Problem description, from Project Euler

There exists exactly one Pythagorean triplet for which a + b + c = N. (N is known.) Find the product abc.

Solution

This was a quick once since I just brute-forced it. I think there are some optimizations possible related to the idea that a^2 + b^2 < c^2.

; flattens a nested list
(defn flatten [x] (let [s? #(instance? clojure.lang.Sequential %)] (filter (complement s?) (tree-seq s? seq x))))
; returns the result of the pythagorean equation
(defn pythagorean-triplet-c [a b]
    (. java.lang.Math 
        (sqrt 
            (+ (* a a) 
                (* b b)
                )
            )
        )
    )

; returns the c term of a pythagorean triple
; nil if natural term does not exist
(defn pythagorean-triplet-c-natural [a b]
    (def result (pythagorean-triplet-c a b))
    (if (zero? (- result (int result)))
        (int result)
        nil
        )
    )
(defn problem09 [sum]<br />
    (def res<br />
        (map 
            (fn [a]
                (map 
                    (fn [b]
                        (def c (pythagorean-triplet-c-natural a b))
                        (if (and (not (nil? c))
                                (= sum (+ a b c))
                                )
                            (* a b c)
                            nil
                            )
                        )
                        (range 100 sum)
                    )
                )
            (range 100 sum)
            )
        )
    (first (distinct (filter #(not (nil? %)) (flatten res))))
    )

Comments are closed.