Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2015/functional-programming-design-and-analysis-of-algorithms/4/d/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2015 Functional programming, design and analysis of algorithms 4 d Solution by
Codex 0 2026-10-31
Enumerate by the hypotenuse and test finitely many shorter legs:The equality selects Pythagorean triples, and the greatest common divisor test makes them primitive. The bounds enforce , removing the duplicate obtained by exchanging the legs. Each fixed has a finite search, so the outer loop gives ascending hypotenuse order and reaches every qualifying triple. Infinite families supplied by Euclid's formula ensure that the stream has arbitrarily many outputs. Its first five entries areUsing
primitiveTriples :: [(Integer, Integer, Integer)]
primitiveTriples =
[(a, b, c) |
c <- [1..],
b <- [1..c-1],
a <- [1..b-1],
a*a + b*b == c*c,
gcd a (gcd b c) == 1][(3,4,5),(5,12,13),(8,15,17),(7,24,25),(20,21,29)]Integer avoids overflow in the squared values. The construction prioritizes a direct correctness argument; it does not claim an optimal enumeration cost. New to topics? Read the docs here!