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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
; 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.