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.

Revisions

  1. deepakkumarnd created this gist Jun 25, 2019.
    15 changes: 15 additions & 0 deletions fibonacci.sc
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    // 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))