View Category

Find all Pythagorean triangles with length or height less than or equal to 20

Pythagorean triangles are right angle triangles whose sides comply with the following equation:

a * a + b * b = c * c

where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:

[3, 4, 5]
[6, 8, 10]
[5, 12, 13]
[9, 12, 15]
[8, 15, 17]
[12, 16, 20]
[15, 20, 25]
clojure
(defn pythagorean [a b c] (= (+ (* a a) (* b b)) (* c c)))

(defn intsqrt [cc]
(. (. Math sqrt cc) intValue)
)

(defn triples [maxSize]
(filter not-empty
(for [a (range 1 20) b (range a 20)]
(let [c (intsqrt (+ (* a a) (* b b)))]
(if (pythagorean a b c)
[a b c]
()
)))))

(triples 20)
; -> ([3 4 5] [5 12 13] [6 8 10] [8 15 17] [9 12 15] [12 16 20] [15 20 25])

(defn sortByHypotenuse [triples]
(sort-by #(first (rest (rest %))) triples)
)

(sortByHypotenuse (triples 20))
; -> ([3 4 5] [6 8 10] [5 12 13] [9 12 15] [8 15 17] [12 16 20] [15 20 25])
(doseq [pt (sort-by #(% 2)
(for [a (range 1 21)
b (range a 21)
:let [aa+bb (+ (* a a) (* b b))
c (Math/round (Math/sqrt aa+bb))]
:when (= aa+bb (* c c))]
[a b c]))]
(println pt))
(->> (for [a (range 1 21) b (range 1 21)] [a b (Math/sqrt (+ (* a a) (* b b)))])
(filter #(-> % last (mod 1) zero?))
(sort-by last))

Greatest Common Divisor

Find the largest positive integer that divides two given numbers without a remainder. For example, the GCD of 8 and 12 is 4.

clojure
(defn gcd [a b]
(if (zero? b)
a
(recur b (mod b a))))