Created
September 11, 2014 16:04
-
-
Save pocketkk/7d8adf4ceb37f05b96b7 to your computer and use it in GitHub Desktop.
Swift - Factorial and 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
//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