Created
May 11, 2017 07:20
-
-
Save timaschew/0c94d6f6947c378b94900b71bd3b766b to your computer and use it in GitHub Desktop.
fibonacci in scala
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
def fibonacci (n: Int): Int = { | |
@tailrec | |
def fib (start: Int, prev: Int, prevPrev: Int = 0): Int = { | |
start match { | |
case start if (start == n) => prev | |
case _ => fib(start + 1, prev + prevPrev, prev) | |
} | |
} | |
n match { | |
case _ => fib(1, 1) | |
} | |
} |
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
def fibonacci (n: Int): Int = { | |
@tailrec | |
def fib (n: Int, prev: Int, sum: Int = 0): Int = { | |
n match { | |
case 0 => sum | |
case _ => fib(n - 1, prev + sum, prev) | |
} | |
} | |
fib(n, 1) | |
} |
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
def fibonacci (n: Int): Int = n match { | |
case 1 => 1 | |
case 2 => 1 | |
case m => fib(n-1) + fib(n-2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment