+ 3

Someone who can help translate this code

func fib(n: Int) -> Int { return n < 2 ? n : (fib(n-1) + fib(n-2)) } print(fib(3))

10th Dec 2015, 3:11 PM
Heinrich Frausing
2 Respuestas
+ 8
The function calls itself recursively, until n is equal to 0 or 1, at which point the recursion ends. return n < 2 ? n : (fib(n-1) + fib(n-2)), means if n is less than 2 return n, otherwise calculate (fib(n-1) + fib(n-2)) Lets consider the example when n=3 (fib(3)) 1. checks n=3 < 2 nope, calculates fib(2) + fib(1) 2. calls fib(2) 3. checks n=2 < 2 nope, calculates fib(1) + fib(0) 4. calls fib(1) 5. checks n=1 < 2 yes, returns 1 6. calls fib(0) 7. checks n=0 < 2 yes, returns 0 8. calls fib(1) (from point 1.) 9. checks n=1 < 2 yes, returns 1 According to the recursion: fib(3) = fib(2) + fib(1) = fib(1) + fib(0) + fib(1) = 1 + 0 + 1 = 2
17th Jan 2016, 3:51 AM
Paruyr Danielian
Paruyr Danielian - avatar
+ 1
The answer above is very explicit and clear. Thank you @Paruyr Danielian. The function is a famous fibonachi's series. Can someone tell me the use in real life of this function.
5th Aug 2016, 9:35 PM
Abdelkader Ait Assou
Abdelkader Ait Assou - avatar