Last active
November 11, 2024 19:51
-
-
Save leemorgan/b26288e6909435c3193e to your computer and use it in GitHub Desktop.
Fibonacci series in Swift
This file contains 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
// Fibonacci series | |
// F[n] = F[n-1] + F[n-2] | |
// 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 | |
// Find the fibonacci number for n interations | |
func fibonacci(n: Int) { | |
var num1 = 0 | |
var num2 = 1 | |
for _ in 0 ..< n { | |
let num = num1 + num2 | |
num1 = num2 | |
num2 = num | |
} | |
print("result = \(num2)") | |
} | |
fibonacci(7) | |
// Using Recursion | |
func fibonacciRecursiveNum1(num1: Int, num2: Int, steps: Int) { | |
if steps > 0 { | |
let newNum = num1 + num2 | |
fibonacciRecursiveNum1(num2, num2: newNum, steps: steps-1) | |
} | |
else { | |
print("result = \(num2)") | |
} | |
} | |
fibonacciRecursiveNum1(0, num2: 1, steps: 7) |
func fib(_ N: Int) -> Int {
// Init a bottom up array
var bottomUp: [Int] = []
/**
Add the 3 known starting cases of
the fibonacci sequence
*/
bottomUp.append(0)
bottomUp.append(1)
bottomUp.append(1)
// Check that N is larger than 2
if N > 2 {
// If so, iterate up through N + 1
for index in 3...N + 1 {
// And calculate the fib for that spot
bottomUp.append(bottomUp[index - 1] + bottomUp[index - 2])
}
}
// Return the Nth fib
return bottomUp[N]
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is being a bit clever: