“Fibonacci Series” in Java helps the programmer generate the sequences from the already contained values. It is represented by “Fx+2 = Fx+1 + Fx” where “x” is the current number. It is an infinite series that is easily calculated and the recursion makes this process much easier. In practical life, this series is also used in analyzing the stock market, etc.
What is a Fibonacci Series?
A Fibonacci series is a range of numbers where the next number is the addition of its previous two numbers starting with 0 and 1. For instance, the next Fibonacci series value in the series “0,1” will be the sum of these two values “0 + 1 = 2”, and its next value will be “2 + 1 = 3” and so on.
Demonstration
Input (Fibonacci Series Length)
12
Output
0,1,1,2,3,5,8,13,21,34,55,89
As specified, each number is a sum of its previous two numbers.
How to Calculate Fibonacci Series?
The Fibonacci series can be calculated using the below-given methodologies:
- These series are calculated using some extra variables that act as a template code. This enables the user to specify the values i.e., the last 2 to add and assign the sum to the next value.
- Another method to calculate these series can be to recursively call a function for each value in the series.
How to Generate Fibonacci Series in Java?
Fibonacci series can be generated in Java using the following approaches:
- “for” Loop.
- Recursion.
- Memoization.
- “while” Loop.
- Custom Logic.
Approach 1: Generate Fibonacci Series Using “for” Loop in Java
This approach is the simplest that uses the “for” loop to iterate till the counter value. After that, it assigns the next value the addition/sum of its previous two values.
Example 1: Specified Counter
This example generates the series according to the initialized counter value:
package jbArticles;
public class Fibonacci {
public static void main(String args[]){
int val1 = 0; int val2 = 1;
int count = 12;
System.out.print(val1+" "+val2);
for(int i = 2; i< count; i++) {
int val3 = val1 + val2;
System.out.print(" "+val3);
val1 = val2;
val2 = val3;
}
}
}
Code Explanation
- Initialize the first and second values starting from “0” and “1”, respectively to start the series and return these values accordingly.
- Also, add these values to generate the next value in sequence.
- Use the “for” loop to iterate the values from “2” to the specified counter.
- In the loop body, sum the previous two values to generate the next value and display it.
- Specify the template code to repeat this process for each value till the counter and return the series accordingly.
Output
To generate the Fibonacci series from a specified start value i.e., “2” in this case instead of “0”, consider the below code:
package jbArticles;
public class Fibonacci {
public static void main(String args[]){
int val1 = 2;
int val2 = 3;
int count = 12;
System.out.print(val1 + " " + val2);
for(int i = 2; i< count; i++) {
int val3 = val1 + val2;
System.out.print(" "+val3);
val1 = val2;
val2 = val3;
}
}
}
Code Explanation
The starting value for the series is changed to “2” and the “for” loop is also modified accordingly to generate the Fibonacci series of 12 numbers starting from “2”.
Output
Example 2: User Input Counter
This example generates the Fibonacci series till the user-input counter value:
package jbArticles;
import java.util.Scanner;
public class Fibonacci {
public static void main(String args[]){
int val1 = 0;
int val2 = 1;
Scanner x = new Scanner(System.in);
System.out.println("Enter the number of Fibonacci Series to Generate: ");
int count = x.nextInt();
System.out.print(val1+" "+val2);
for(int i = 2; i< count; i++) {
int val3 = val1 + val2;
System.out.print(" "+val3);
val1 = val2;
val2 = val3;
} }
}
Code Explanation
- Import the given library to input the values from the user.
- Initialize the first two values of the series and create a Scanner object to enable user input.
- Use the “nextInt()” method to take the counter values as an integer.
- Display the first two values and likewise, use the “for” loop to iterate to the counter.
- In iteration, return the current value as the sum of the last two values in each case in the series.
Output
Approach 2: Generate Fibonacci Series Using Recursion in Java
In “Recursion”, a function is called repeatedly within the same function. This approach generates these series by calling a function recursively for each value in the series:
package jbArticles;
public class Fibonacci {
static int x1= 0, x2= 1, x3= 0;
static void generateFibonacci(int counter){
if((counter-2) > 0){
x3 = x1 + x2;
x1 = x2;
x2 = x3;
System.out.print(" "+x3);
generateFibonacci(counter-1);
}}
public static void main(String args[]){
int counter = 15;
System.out.print(x1+" "+x2);
generateFibonacci(counter);
}
}
Code Explanation
- Initialize the given integer values to specify the logic for the series.
- Define the function “generateFibonacci()” having the counter to be passed as its parameter. In its definition, subtract “2” from the passed counter and check if it is greater than “0”.
- Note: This subtraction is done as the first “2” values of the Fibonacci series will be printed manually.
- Upon the satisfied condition, assign the sum of the last two values to the current value and repeat the process for all the values.
- Decrement the counter by 1 to apply the Fibonacci sequence to all the values.
- In “main”, initialize the counter to display the series accordingly.
- Log the first two values on the console to generate the series accordingly.
- Call the function by passing the “counter” value as its argument.
Output
Note: The time complexity for this approach is “O(2^n)”.
Approach 3: Generate Fibonacci Series Using Memoization in Java
To improve the performance of the above “Recursion” approach, the memoization approach is used that reduces the time complexity to “O(n)”. In this technique, the series numbers are calculated only once and are contained in the array:
package jbArticles;
public class Fibonacci {
public static void main(String[] args) {
int count = 10;
int[] array = new int[count];
for (int i = 0; i < count; i++) {
System.out.print(generateFibonacci(i, array) + " ");
}
}
public static int generateFibonacci(int x, int[] passArray) {
if (passArray[x] != 0)
return passArray[x];
if (x == 0 || x == 1)
return 1;
else {
passArray[x] = generateFibonacci(x - 1, passArray) + generateFibonacci(x - 2, passArray);
return passArray[x];
} } }
Code Explanation
- Assign the counter value and declare an array in which the series is to be stored.
- This array has a size equal to the counter value.
- Use the “for” loop to iterate from “0” to “9” to include 10 values in the array by accessing the function “generateFibonacci()”.
- Define the function “generateFibonacci()” that takes the pointed array values and the array as its arguments.
- In its definition, return “1” against the first and second indexes/values in the series.
- For the remaining values, invoke the function recursively twice to point to the previous two values of the current value in the array and add them.
Output
Approach 4: Generate Fibonacci Series Using “while” Loop in Java
The “while” loop can also be used to return the Fibonacci series by applying a check on the counter value using a user-defined function:
package jbArticles;
public class Fibonacci {
static void generateFibonacci(int counter) {
int x = 0, y = 1, z = 0;
int count = 0;
while (count<counter) {
System.out.print(x + ", ");
z = x+y;
x = y;
y = z;
count = count+1;
}
}
public static void main(String args[]){ generateFibonacci(10);
}
}
Code Explanation
- Define the function “generateFibonacci()” that takes the counter value as its argument.
- In its definition, initialize the given values based on which the series will be returned.
- Initialize the “count” value and check if it is less than the passed counter.
- If so, log the number of values in the series according to the passed counter.
- Increment the “count” value to display all the values till the counter.
- In “main”, invoke the defined function by passing the counter value.
Output
Approach 5: Generate Fibonacci Series Using Custom Logic in Java
This method uses an additional array to contain the series and return them using array indexing and the “for” loop:
package jbArticles;
public class Fibonacci {
public static void main(String args[]){
int counter = 10;
int array[] = new int[counter + 1];
int i;
array[0] = 0;
array[1] = 1;
for (i = 2; i <= counter; i++) {
array[i] = array[i - 1] + array[i - 2];
System.out.print(array[i] + " ");
}
}}
Code Explanation
- Initialize the counter value and declare an array of size “1” greater than counter to apply the logic appropriately.
- It is such that “11” values will be returned in a series.
- Assign the first and second values in the series.
- Use the “for” loop to generate the series from the 2nd index i.e., 3rd value onwards in the array.
- Apply the logic for adding the sum of the last two values using array indexing.
- Display the array values returned as series.
Output
How to Generate Fibonacci Series Till a Specific Number in Java?
This series can also be displayed till a required number. It implies that the series will not exceed this number and will be displayed within the range.
Below is the code demonstration:
package jbArticles;
public class Fibonacci {
public static void main(String args[]){
int x = 0, y = 1, z = 0;
int number = 115;
while (x<number) {
System.out.print(x + ", ");
z = x+y;
x = y;
y = z;
x = x+1;
} }
}
Code Explanation
Initialize the values and the max number such that the series is displayed till this number. Check for the condition in the “while” loop and likewise, display the series till the number rather than the counter value.
Output
Conclusion
In the Fibonacci series, the present/current number is the sum of its last two numbers. It can be generated using the “for” loop, Recursion, Memoization, “while” Loop, or via custom logic. The “for” loop approach is recommended as it is the simplest, has good space complexity, and can easily be modified as per the requirements.