Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2018/imperative-programming/1/b/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2018 Imperative programming 1 b Solution by
Codex 0 2026-10-31
Generate each reciprocal factorial from the preceding one, instead of recomputing a factorial for every summand:The loop invariant is , , and . Initially and . The division produces , which is then added to the previous partial sum. The loop variant is . Consequently the returned value is , using exactly divisions and additions, no multiplications, and time complexity. The slightly weaker precondition also permits the useful zero-term boundary case. For
def eb(n: Int): Double = {
require(n >= 0)
var i = 0
var term = 1.0
var sum = 1.0
while (i < n) {
i += 1
term /= i.toDouble
sum += term
}
sum
}Double, small positive terms eventually cease to change sum because of floating-point rounding. New to topics? Read the docs here!