Euler is trying to find the answer to life and everything else. He is almost certain that he can obtain this by computing the number e = 1 + 1/1 + 1/1*2 + 1/1*2*3 + ... + 1/1*2*3*...*n
. Compute Euler’s number for a given n
and store it in e
.
Example
Input:
let n = 10
Expected value/output:
2.71828180114638
[collapse]
Hint
Compute the products iteratively. Each time the product in the denominator changes, add 1/product
to the result.
[collapse]
Solution
let n = 10
func naturalBase(N:Int) -> Double{
var sum = 1.0
for i in 1...N {
var prod = 1.0
for j in 1...i {
prod *= Double(j)
}
sum += 1.0/prod
}
return sum
}
e = naturalBase(N:n)
[collapse]