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]
ocaml
let is_int v =
v = (snd (modf v))

let sort_by_third tup =
let third (_,_,v) = v in
let cmp a b = compare (third a) (third b) in
List.sort cmp tup

let hypi ia ib =
let hyp a b = sqrt(a**2.0 +. b**2.0) in
hyp (float_of_int ia) (float_of_int ib)

let find_pythag max =
let rec py t = match t with
| (a,_) when a > max -> []
| (a,b) when b > max -> py (a+1,a+1)
| (a,b) ->
let next = (a,b+1) in
let cf = hypi a b in
if (is_int cf) then
( a,b,(int_of_float cf) ) :: (py next)
else
py next
in
sort_by_third ( py (1,1) )

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.

ocaml
(* tail recursive *)
let rec gcd n m =
if m = 0 then
n
else if n > m then
gcd (n-m) m
else
gcd n (m-n)
;;