Last active
November 29, 2020 18:40
-
-
Save 0xMarK/2ce5c617dd33720bf0bf19e277582088 to your computer and use it in GitHub Desktop.
Fibonacci
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func fibonacciRecursive(_ index: Int) -> Int { | |
if index < 2 { | |
return index | |
} | |
return fibonacciRecursive(index - 2) + fibonacciRecursive(index - 1) | |
} | |
func fibonacciIterative(_ index: Int) -> Int { | |
if index < 2 { | |
return index | |
} | |
var result = 0 | |
var prev = 1 | |
var prevPrev = 1 | |
for _ in 2...index { | |
result = prev + prevPrev | |
prevPrev = prev | |
prev = result | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment