Skip to content

Instantly share code, notes, and snippets.

@timaschew
Created May 11, 2017 07:20
Show Gist options
  • Save timaschew/0c94d6f6947c378b94900b71bd3b766b to your computer and use it in GitHub Desktop.
Save timaschew/0c94d6f6947c378b94900b71bd3b766b to your computer and use it in GitHub Desktop.
fibonacci in scala
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)
}
}
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)
}
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