Fibonacci Series Using Recursive Approach
Since Fibonacci Number is the summation of the two previous numbers. We can use recursion as per the following conditions:
- Get the number whose Fibonacci series needs to be calculated.
- Recursively iterate from value N to 1:
- Base case: If the value called recursively is less than 1, the return 1 the function.
- Recursive call: If the base case is not met, then recursively call for the previous two values as:
recursive_function(N – 1) + recursive_function(N – 2);
- Return statement: At each recursive call(except the base case), return the recursive function for the previous two values as:
recursive_function(N – 1) + recursive_function(N – 2);
Below is the implementation of the Fibonacci Series Using Recursion in Java:
// Recursive implementation of Fibonacci series program in
// java
import java.io.*;
class GFG {
// Function to print the fibonacci series
static int fib(int n)
{
// Base Case
if (n <= 1)
return n;
// Recursive call
return fib(n - 1) + fib(n - 2);
}
// Driver Code
public static void main(String args[])
{
// Given Number N
int N = 10;
// Print the first N numbers
for (int i = 0; i < N; i++) {
System.out.print(fib(i) + " ");
}
}
}
Output
0 1 1 2 3 5 8 13 21 34
The complexity of the above method
Time Complexity: O(2N)
Auxiliary Space: O(n)
Program to Print Fibonacci Series in Java
The Fibonacci series is a series of elements where, the previous two elements are added to get the next element, starting with 0 and 1. In this article, we will learn how to print Fibonacci Series in Java up to the N term, where N is the given number.
Examples of Fibonacci Series in Java
Input: N = 10
Output: 0 1 1 2 3 5 8 13 21 34
Explanation: Here first term of Fibonacci is 0 and second is 1, so that 3rd term = first(o) + second(1) etc and so on.
There are 4 ways to write the Fibonacci Series program in Java:
- Fibonacci Series Using Iterative Approach
- Fibonacci Series Using Recursive Approach
- Fibonacci Series Using Memoization
- Fibonacci Series Using Dynamic Programming