Skip to content

Instantly share code, notes, and snippets.

@pocketkk
Created September 11, 2014 16:04
Show Gist options
  • Save pocketkk/7d8adf4ceb37f05b96b7 to your computer and use it in GitHub Desktop.
Save pocketkk/7d8adf4ceb37f05b96b7 to your computer and use it in GitHub Desktop.
Swift - Factorial and Fibonacci
//Factorial
func fact(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n * fact(n-1)
}
}
fact(15)
//Fibonacci
func fib(n: Int) -> Int {
var f = 0
if n <= 2 {
return 1
} else {
f = fib(n-1) + fib(n-2)
}
return f
}
fib(8)
//Fibonacci with memoization
var memo = [Int: Int]()
func fib2(n: Int) -> Int {
var f = 0
if memo[n] != nil {
return memo[n]!
}
if n <= 2 {
f = 1
} else {
f = fib2(n-1) + fib2(n-2)
}
memo[n] = f
return f
}
fib2(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment