+ 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))

30th Apr 2018, 8:41 PM
Aarnav
2 Réponses
+ 3
thank you
30th Apr 2018, 8:57 PM
Aarnav
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.
30th Apr 2018, 8:45 PM
Ali Zhussupov
Ali Zhussupov - avatar