scala: Fibonacci series nth number recursion

Write a recursive function to get the nth Fibonacci number (http://mng.bz/C29s).
The first two Fibonacci numbers are 0 and 1. The nth number is always the sum of the
previous two—the sequence begins 0, 1, 1, 2, 3, 5. Your definition should use a
local tail-recursive function.

 

 

Solution:

object fibonaci extends App{

def fibonaci(n:Int)=
{
def fibgo(n:Int,prev:Int=0,next:Int=1):Int= n match
{
case 0 => prev
case 1 => next
case _ => fibgo(n-1,next,(next+prev))

}

fibgo(n)
}

println(fibonaci(8))
}

 

 

 

Thanks

Regards

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s