Permalink
Browse files

Function to compute the nth Fibonacci number

  • Loading branch information...
1 parent 7b96234 commit 2d323df20d3990e2ad7df9be7a2567a390972d53 @rboles committed Feb 26, 2014
Showing with 11 additions and 1 deletion.
  1. +11 −1 exercises/src/main/scala/fpinscala/gettingstarted/GettingStarted.scala
@@ -36,7 +36,17 @@ object MyModule {
// Exercise 1: Write a function to compute the nth fibonacci number
- def fib(n: Int): Int = ???
+ def fib(n: Int): Int = {
+
+ def go(x: Int, y: Int, i: Int): Int = {
+ if ( i == n ) x + y
+ else go(y, x+y, i+1)
+ }
+
+ if ( n == 0 ) 0
+ else if ( n == 1 ) 1
+ else go(0, 1, 2)
+ }
// This definition and `formatAbs` are very similar..
private def formatFactorial(n: Int) = {

0 comments on commit 2d323df

Please sign in to comment.