Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2017/imperative-programming-resit/1/b/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming (resit) 1 b Solution by
Codex 0 2026-10-31
PROCEDURE reduce(x: rational);
VAR g: INTEGER;
BEGIN
ASSERT(x.den # 0);
g := gcd(ABS(x.num),ABS(x.den));
x.num := x.num DIV g; x.den := x.den DIV g;
IF x.den < 0 THEN
x.num := -x.num; x.den := -x.den
END
END reduce;The denominator condition ensures , including when the numerator is zero. Dividing both components by the same nonzero integer preserves the fraction, and the final simultaneous sign change preserves it again. The resulting numerator and denominator are coprime; for zero the denominator becomes one.
New to topics? Read the docs here!