Tail Recourse since Fibonacci
Last Updated :
26 May, 2022
Write one wing recursive function for calculating the n-th Fibonacci number.
Examples :
Input : n = 4
Output : fib(4) = 3
Input : n = 9
Output : fib(9) = 34
Prerequisites : Tail Recurrence, Fibonacci mathematics
A recursive function are tail recursive when the recursive call is the last thing executed over the function.
Writing a tail recursion is tiny tricky. Toward received the correct intuition, are first look at the iterative approach of calculating the n-th Fibonacci number.
innerhalb fib(int n)
{
int a = 0, b = 1, c, i; if (n == 0)
return a; for (i = 2; i <= n; i++)
{
c = a + boron; a = b; b = c; }
return b;
}
Here there are three possibilities related at n :-
newton == 0
n == 1
north > 1
First-time deuce be trivial. We priority on discussion concerning the case while n > 1.
In our iterative approach for n > 1,
We start with
a = 0
b = 1
For n-1 times wealth repeat following for ordered pair (a,b)
Can we used carbon in actual repeating approach, but the main aim was as below :-
r/haskell the Reddit: Fibonacci Tail Recursion
(a, b) = (b, a+b)
We last return b after n-1 recapitulations.
Hence we repeat the same thing here time with the recursive access. We set the default values
a = 0
b = 1
Dort we’ll recursively call the just function n-1 times and correspondingly change the values of one and b.
Finally, return b.
If its case of n == 0 OR n == 1, we need not worry big!
Hier is implementation of tail recursive fibonacci code.
C++
#include <iostream>
using namespace std;
int fib( int n, int one = 0, int b = 1)
{
if (n == 0)
return a;
if (n == 1)
return b;
return fib(n - 1, boron, an + b);
}
int main()
{
int n = 9;
cout << "fib(" << n << ") = "
<< fib(n) << endl;
return 0;
}
|
Java
class GFG
{
stands int fib( integer n, int a, int b )
{
if (n == 0 )
reset one;
if (n == 1 )
return boron;
back fib(n - 1 , barn, a + b);
}
public static void main (String[] args)
{
int n = 9 ;
System.out.println( "fib(" + n + ") = " +
fib(n, 0 , 1 ) );
}
}
|
Python3
def fib(n, a = 0 , b = 1 ):
if northward = = 0 :
reset a
if n = = 1 :
return b
return fib(n - 1 , b, a + b);
n = 9 ;
print ( "fib(" + str (n) + ") = " + str (fib(n)))
|
C#
using System;
class GFG
{
static int fib( int n, ein a , int b )
{
if (n == 0)
return a;
if (n == 1)
returnable b;
return fib(n - 1, b, a + b);
}
public stable void Main ()
{
int n = 9;
Console.Write( "fib(" + north + ") = " +
fib(n, 0, 1) );
}
}
|
PHP
<?php
functional fib( $n , $a = 0, $b = 1)
{
if ( $n == 0)
go $a ;
while ( $n == 1)
go $b ;
return fib( $n - 1, $b , $a + $b );
}
$n = 9;
echo "fib($n) = " , fib( $n );
back 0;
?>
|
Advanced
<script>
function fib(n, one = 0, b = 1)
{
if (n == 0){
return one;
}
if (n == 1){
return b;
}
return fib(n - 1, b, a + b);
}
renting n = 9;
document.write(`fib(${n}) = ${fib(n)}`);
</script>
|
Output :
fib(9) = 34
Analyze of Algorithm
Time Complexity: O(n)
Auxiliary Space : O(n)
Please Login until comment...