Skip to content

Instantly share code, notes, and snippets.

@deepakkumarnd
Created June 25, 2019 08:43
Show Gist options
  • Save deepakkumarnd/ef4246be761f94044c8a24204ae76adf to your computer and use it in GitHub Desktop.
Save deepakkumarnd/ef4246be761f94044c8a24204ae76adf to your computer and use it in GitHub Desktop.
nth fibonacci number
// find nth fibonacci number
def fib(n: Int): Int = {
@annotation.tailrec
def loop(a: Int, b: Int, acc: Int): Int =
if (acc > 0) loop(b, a + b, acc - 1)
else b
if (n < 1) throw new Exception(s"Can't find ${n}th term")
else if(n == 1) 0
else if (n == 2) 1
else loop(0, 1, n - 2)
}
println(fib(40))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment