To solve the Fibonacci series problem in Java, you can use iterative, recursive, or dynamic programming approaches. The Fibonacci series is a sequence where each number is the sum of the two preceding ones, starting with 0 and 1. Here’s how to implement it step-by-step.
In this blog, we will understand the concept of Fibonacci series in Java language. But before going ahead, we need to understand the Fibonacci series and its properties. The Fibonacci series in Java is a series of numbers in which each member is obtained by adding the previous two members. Each item of the Fibonacci series is called a Fibonacci number.
Excerpt of Fibonacci Series Problem in Java
The Fibonacci series problem is a common coding challenge where each term in the sequence is the sum of the two preceding ones. Implementing this in Java can be done using various techniques, including recursion for a direct but less efficient approach, iteration for a more optimized solution, or dynamic programming for high-performance applications. Understanding these methods can sharpen your problem-solving skills.
Steps to Generate Fibonacci Series in Java
Iterative Method:
public class FibonacciIterative {
public static void main(String[] args) {
int n = 10; // Number of terms
int first = 0, second = 1;
System.out.print(first + " " + second + " ");
for (int i = 2; i < n; i++) {
int next = first + second;
System.out.print(next + " ");
first = second;
second = next;
}
}
}
Recursive Method:
public class FibonacciRecursive {
public static void main(String[] args) {
int n = 10; // Number of terms
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
public static int fibonacci(int n) {
if (n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
How to Solve Fibonacci Series Problem in Java
- Using Iteration:javaCopy code
public class Fibonacci { public static void main(String[] args) { int n = 10; // number of terms int a = 0, b = 1; System.out.print("Fibonacci Series: " + a + ", " + b); for (int i = 2; i < n; i++) { int c = a + b; System.out.print(", " + c); a = b; b = c; } } }
- Using Recursion:javaCopy code
public class FibonacciRecursion { public static void main(String[] args) { int n = 10; for (int i = 0; i < n; i++) { System.out.print(fibonacci(i) + " "); } } public static int fibonacci(int n) { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); } }
- Using Dynamic Programming:javaCopy code
public class FibonacciDP { public static void main(String[] args) { int n = 10; int[] fib = new int[n]; fib[0] = 0; fib[1] = 1; for (int i = 2; i < n; i++) { fib[i] = fib[i - 1] + fib[i - 2]; } for (int num : fib) { System.out.print(num + " "); } } }
- Using Streams (Java 8+):javaCopy code
import java.util.stream.Stream; public class FibonacciStreams { public static void main(String[] args) { Stream.iterate(new int[]{0, 1}, f -> new int[]{f[1], f[0] + f[1]}) .limit(10) .forEach(f -> System.out.print(f[0] + " ")); } }
To comprehend this model, you ought to realize the essential Java programming subjects like capabilities, circles, contingent proclamations, and so on. So kindly allude to those subjects prior to hopping into the Fibonacci series in java issue.
Eg :- 0,1,1,2,3,5,8,13,21,34 etc is an example of fibonacci series
The first Fibonacci numbers are 0 and 1, respectively
F(N) = F(N-1)+F(N-2)
The above expression is the general equation followed by every Fibonacci number. The above equation also helps us to find the following Fibonacci numbers.
Next, we will discuss printing the Fibonacci series in Java. There are multiple ways in which one could print the Fibonacci series in Java. But we will discuss the most common one in detail. We will also briefly discuss the other crucial method.
- Print Fibonacci Series in Java using Recursion
- Print Fibonacci Series in Java Iteratively
Print Fibonacci Series in Java using Recursion
Since the Fibonacci Number is nothing but the summation of the two previous numbers, we can use Recursion with the following condition:
- Get which Fibonacci series term needs to be calculated, i.e., 1st,2nd,3rd etc.
- Recursively iterate from value N to 1:
- Base case: Here, we need to specify two conditions to meet the base case, i.e., if n is equal to 1 or n is equal to 0, return n.Since we are making two recursive calls at one time for fib_2, we will call fib_1 and fib_0. If we specify the base case only when n equals 1, our code will get a recursion depth error since fib_0 will not meet the base case.
- Recursive call: If the base case condition is not met, then we will make a recursive call for the last two numbers, i.e., n-1,n-2 as:
recursive_function(N – 1) + recursive_function(N – 2);
- Return statement: At each recursive call, return the sum of the Fibonacci value of the previous two numbers found using recursion
recursive_function(N – 1) + recursive_function(N – 2);
Below we can see the implementation of the above approach:
Code:-
//Import scanner
import java.util.Scanner;
// Fibonacci Series in Java using Recursion Implementation
class coding_ninja {
// Function to print the fibonacci series
public static int fibonacci(int n) {
// Base Case
if (n==1||n==0) {
return n;
}
// Recursive call
return fibonacci(n – 1)+ fibonacci(n – 2);
}
// Main Function
public static void main(String [] args) {
// Create scanner object
Scanner sc = new Scanner(System.in);
// Take N input
int N = sc.nextInt();
// Print the first N numbers
for (int i = 0; i < N; i++) {
System.out.print(fibonacci(i) + “,”);
}
}
}
Output:-
8
0,1,1,2,3,5,8,13,
Print Fibonacci Series in Java Iteratively
For printing the Fibonacci series in Java using iteration, we first need to Initialize the first and second numbers to 0 and 1 (These two num1 and num2 represent the first two numbers of the series). Following this, we will print the first and second numbers. After that, we will enter the flow to the iterative for a loop. We will get the next series member by adding the previous two members. Simultaneously, we swap the first number with the second number and the second number with the third number.
Code:-
// Import scanner
import java.util.Scanner;
public class coding_ninja {
// Fibonacci Function
public static void Fibonacci(int N) {
// Initialising the first two fibonacci number
int num1 = 0, num2 = 1;
// Initialising Counter
for(int i=0;i<N;i+=1) {
System.out.print(num1+”,”);
// Swap
int num3 = num2 + num1;
num1 = num2;
num2 = num3;
}
}
public static void main(String[] args) {
// Create scanner object
Scanner sc = new Scanner(System.in);
// Take N input
int N = sc.nextInt();
// Call fibonacci function to get N fibonacci Numbers
Fibonacci(N);
// Close Scanner
sc.close();
}
Output:-
8
0,1,1,2,3,5,8,13,
Approach: (Dynamic Programming)
The Third approach for the Fibonacci series in Java problem is as follows.
- Create an array arr1[] of size N.
- Initiate arr1[0] = 0, arr1[1] = 1.
- Loop over [2, N] and update the following array arr1[] as:
- arr1[i] = arr1[i – 2] + arr1[i – 1]
- Print the value of arr1[N].
Example for Fibonacci series
Example : Let’s take a number N=7.
Code
// Program to print Fibonacci series in java
// Dynamic Programming approach for
// Fibonacci Series
class fab {
// Function to find the N fibonacci Series
static int fib_series(int n)
{
// initialize an array to store Fibonacci numbers.
// 1 extra to handle case, n = 0
int fx[] = new int[n + 2];
int i;
// 0th and 1st number of
// the series are 0 and 1
fx[0] = 0;
fx[1] = 1;
for (i = 2; i <= n; i++) {
// Add the last 2 numbers
// in the series and store it
fx[i] = fx[i – 1] + fx[i – 2];
}
// Nth Fibonacci Number
return fx[n];
}
public static void
main(String args[])
{
// provide Number N
int N = 7;
// Print first 10 Fibonacci Number
for (int i = 0; i < N; i++)
System.out.print(fib_series(i) + ” “);
}
}
Output
0 1 1 2 3 5 8
There are numerous ways to solve or get the n Fibonacci number series. Other than the above-discussed codes. We could tweak the above code in different ways, i.e., by using a while loop, creating a method for Fibonacci number calculation, and much more. But some effective or promising approaches could be used to get the Fibonacci series in Java.
- The first method is using Recursion, which we have explained above.
- The second method is by using Dynamic Programming. Repeated work done in the recursion method code could be avoided by storing the Fibonacci numbers we have calculated.
- Another method to get the Fibonacci series in Java is using the direct formula for the nth term of the Fibonacci series.
Fn = {[(√5 + 1)/2] ^ n} / √5
- One more way to get the nth Fibonacci series is Using the power of the matrix {{1, 1}, {1, 0}}: This approach is another O(n) time .The solution to the method is if we multiply n times the matrix M = {{1,1},{1,0}} to itself (in other words,we are calculating power(M, n)), then we will get the (n+1)th Fibonacci number as the element at the row 0 and column 0 i.e, at index (0, 0) in the resultant matrix.
- The discussed approach could be optimized to work in O(Logn) time complexity. We could reduce the time complexity by making a recursive multiplication to get power(M, n)
Conclusion
In this article, we have learned about the Fibonacci series. We have discussed multiple concepts about it and learned how to print the Fibonacci series in java easily. In Java, multiple concepts can be learned at an initial and mid-level to get expertise in Java. Some concepts include final keywords in java, java basics, oops concepts etc.
The Fibonacci series is a sequence where each number is the sum of the two preceding numbers. In Java, it can be implemented using iterative or recursive methods.
Use a recursive method like:
java
Copy codepublic static int fibonacci(int n) { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); }
Dynamic programming is the most efficient way, as it stores previously computed values to avoid redundant calculations, improving performance.
Yes, Java 8 Streams allow generating the Fibonacci series concisely with the Stream.iterate()
method for functional programming.