+ 3
How does func fib(n: Int) -> Int { return n < 2 ? n : (fib(n-1) + fib(n-2)) } print(fib(3)) have an output of 2
func fib(n: Int) -> Int { return n < 2 ? n : (fib(n-1) + fib(n-2)) } print(fib(3))
2 ответов
+ 3
thank you
0
This function returns n-th fibonacci:
if n < 2 : f(0) = 0, f(1) = 1
if n >= 2: f(n) = f(n-1) + f(n-2)
Thus, f(2) = f(1) + f(0) = 1,
And
f(3) = f(2) + f(1) = 1 + 1 = 2.