Created
June 25, 2019 08:43
-
-
Save deepakkumarnd/ef4246be761f94044c8a24204ae76adf to your computer and use it in GitHub Desktop.
nth fibonacci number
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
// 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