Fibonaci Recursion

Run Settings
LanguageSwift
Language Version
Run Command
// Given a number N return the index value of the Fibonacci sequence, where the sequence is: // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ... // the pattern of the sequence is that each value is the sum of the 2 previous values, that means that for N=5 → 2+3 //For example: fibonacciRecursive(6) should return 8 func fibonacciIterative(_ n: Int) -> Int { var fib = [0, 1] for i in 2...n { fib.append(fib[i - 1] + fib[i - 2]) } return fib[n] } print(fibonacciIterative(6)) func fibonacciRecursive(_ n: Int) -> Int { if n < 2 { return n } return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2) } print(fibonacciRecursive(3))
Editor Settings
Theme
Key bindings
Full width
Lines