The Golden Ratio

Fibonacci is trying to find the answer to life and everything else. He is sure this secret can be revealed by understanding this weird number which occurs in nature and has a strange aestethical beauty: 1+1/(1+1/(1+1/(1+...))). Unfortunately, he only has n more years to live and needs the help of a programmer to approximate the number to a precision of n digits. Are you the one to help the master enjoy his last years of life? Compute this number and store it in phi.

TheGoldenRatio

Example

Input:

let depth = 20

Expected value/output:

1.61803398501736

[collapse]
Hint

Recursively compute 1 + 1/goldenRatio until you reach the desired depth.

[collapse]
Solution

let depth = 20
func goldenRatio(depth:Int) -> Double {
    if depth == 0 {
        return 1.0
    }
    else {
        return 1.0 + 1.0/goldenRatio(depth: depth - 1)
    }
}

phi = goldenRatio(depth:depth)

[collapse]
Subscribe
We send about one email per week with our latest tutorials and updates
Never display this again :)