0% found this document useful (0 votes)
53 views1 page

Fibonacci Series Using Recursion in Java

Uploaded by

nayan.sawant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views1 page

Fibonacci Series Using Recursion in Java

Uploaded by

nayan.sawant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Fibonacci Series Using recursion in Java

To calculate the Fibonacci Series using recursion in Java, we need to create a function so that we
can perform recursion. This function takes an integer input. The function checks whether the
input number is 0, 1, or 2, and it returns 0, 1, or 1(for 2nd Fibonacci), respectively, if the input is
any one of the three numbers.

If the input is greater than 2, the function calls itself recursively for the previous values until the
value of the input variable becomes less than or equal to 2. So if the function receives an integer
n as input, it will return the nthnth Fibonacci number. To print the Fibonacci series, we will call
this function to compute each Fibonacci number.

public class FibonacciCalc {


public static int fibRecursion(int count) {
if (count == 0) {
return 0;
} // Oth fibonacci is 0

if (count == 1 || count == 2) {
return 1;
} // 1st and 2nd Fibonacci are 1 and 1 only

// calling function recursively for nth Fibonacci


return fibRecursion(count - 1) + fibRecursion(count - 2);
}

public static void main(String args[]) {


int fib_len = 9;

[Link]("Fibonacci Series of " + fib_len + " numbers is: \n");

for (int i = 0; i < fib_len; i++) {


[Link](fibRecursion(i) + " ");
}
}
}

Time And Space Complexity

The time complexity of the recursive approach to solving the Fibonacci series is O(2n)O(2n) i.e.
exponential time. The space complexity of the recursive method is O(n), if we consider the
recursive stack.

Exponential time complexity is extremely inefficient. It would take too long to calculate the
Fibonacci series of a huge length using the recursive method. To solve this problem, we can use
the memoization technique to create the Fibonacci Series. This technique is much faster than
the recursive method.

You might also like