Maintain the reciprocal factorial term rather than calculating large factorials separately:
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
}
The exact-arithmetic loop invariant is , , and . It holds for because . Dividing by the new index produces the next reciprocal factorial; adding it extends the partial sum. The loop variant is . At exit the sum includes all terms from through , using exactly divisions and no multiplications in the loop. In particular, the initial 1.0 accounts for the zero-index term. The work bound is , with constant auxiliary space.

Articles by others on the same topic (0)

There are currently no matching articles.