The Natural Base

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.

TheNaturalBase

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]
1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 4.00 out of 5)
Loading...
Subscribe
We send about one email per week with our latest tutorials and updates
Never display this again :)