-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0009.clj
More file actions
executable file
·72 lines (65 loc) · 1.8 KB
/
0009.clj
File metadata and controls
executable file
·72 lines (65 loc) · 1.8 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
(defn brute-force-problem-nine []
(loop [a 3 b 4]
(if (< b (inc a)) ; if a gets greater than or equal to b then increment b
(recur 100 (inc b))
(let [c (int (. Math (sqrt (+ (* a a) (* b b)))))]
(if (and (= (+ a b c) 1000) (= (rem (+ (* a a) (* b b)) c) 0))
(* a b c)
(recur (inc a) b))))))
; derived from the solution shown on project euler site
(defn straightforward-approach [s]
(loop [a 3 b 4]
(if (> a (/ (- s 3) 3))
nil
(if (> b (/ (- s 1 a) 2))
(recur (inc a) (+ a 2))
(let [c (- s a b)]
(if (= (* c c) (+ (* a a) (* b b)))
(* a b c)
(recur a (inc b))))))))
(defn ceil [x]
(int (. Math (ceil x))))
(defn sqrt [x]
(. Math (sqrt x)))
(defn abs [x]
(if (neg? x)
(- x)
x))
(defn gcd
([] 0)
([x] (abs x))
([x y] (if (zero? y)
(abs x)
(recur y (rem x y))))
([x y & more] (reduce gcd (gcd x y) more)))
(defn parametrisation-approach [s]
(let [s2 (/ s 2)]
(let [mlimit (- (ceil (sqrt s2)) 1)]
(loop [m 2]
(if (> m mlimit)
-1
(if (= (rem s2 m) 0)
(let [sm (loop [tsm (/ s2 m)]
(if (= (rem tsm 2) 0)
(recur (/ tsm 2))
tsm))]
(let [result (loop [k (if (= (rem m 2) 1)
(+ m 2)
(+ m 1))]
(if (and (< k (* 2 m)) (<= k sm))
(if (and (= (rem sm k) 0) (= (gcd k m) 1))
(let [d (/ s2 (* k m)) n (- k m)]
(let [a (* d (- (* m m) (* n n)))
b (* 2 d m n)
c (* d (+ (* m m) (* n n)))]
(* a b c)))
(recur (+ k 2)))
nil ; nil here for visual aid. the false of an if returns nil if not supplied
))]
(if (= result nil)
(recur (inc m))
result)))
(recur (inc m))))))))
;(println (brute-force-problem-nine))
;(println (straightforward-approach 1000))
(def solutions (list (fn [] (parametrisation-approach 1000))))