The Wayback Machine - https://web.archive.org/web/20241128094425/https://www.geeksforgeeks.org/java-fibonacci-series/
Open In App

Program to Print Fibonacci Series in Java

Last Updated : 18 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Fibonacci Series Using Iterative Approach

Initialize the first and second numbers to 0 and 1. Following this, we print the first and second numbers. Then we send the flow to the iterative while loop where we get the next number by adding the previous two numbers and simultaneously we swap the first number with the second and the second with the third. 

Below is the implementation of the Iterative Approach to Print Fibonacci Series in Java: 

Java
// Fibonacci series program in java

import java.io.*;

class GFG {
    // Function to print N Fibonacci Number
    static void Fibonacci(int N)
    {
        int num1 = 0, num2 = 1;

        for (int i = 0; i < N; i++) {
            // Print the number
            System.out.print(num1 + " ");

            // Swap
            int num3 = num2 + num1;
            num1 = num2;
            num2 = num3;
        }
    }

    // Driver Code
    public static void main(String args[])
    {
        // Given Number N
        int N = 10;

        // Function Call
        Fibonacci(N);
    }
}

The complexity of the above method

Time Complexity: O(N) 
Auxiliary Space: O(1)

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:

  1. Get the number whose Fibonacci series needs to be calculated.
  2. 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:

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)

Fibonacci Series Using Memoization 

In the above example, Its time complexity is O(2n)  which can be reduced to O(n) using the memoization technique which will help to optimize the recursion method. This is because the function computes each Fibonacci number only once and stores it in the array.

Below is the implementation of the Fibonacci series using memoization:

Java
// Fibonacci series program in java using memoization

import java.io.*;

class GFG {
    public static void main(String[] args)
    {
        // Number of terms to print
        int n = 10;
        int[] memo = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            System.out.print(fibonacci(i, memo) + " ");
        }
    }

    public static int fibonacci(int n, int[] memo)
    {
        if (memo[n] != 0)
            return memo[n];
        if (n == 1 || n == 2)
            return 1;
        else {
            memo[n] = fibonacci(n - 1, memo)
                      + fibonacci(n - 2, memo);
            return memo[n];
        }
    }
}

The Complexity of the above method

Time Complexity: O(n)  
Auxiliary Space: O(n)

Fibonacci Series Using Dynamic Programming

 We can avoid the repeated work done in method 2 by storing the Fibonacci numbers calculated so far.

The steps to writing the Program are mentioned below:

  • Create an array arr[] of size N.
  • Initialize arr[0] = 0, arr[1] = 1.
  • Iterate over [2, N] and update the array arr[] as:   
    • arr[i] = arr[i – 2] + arr[i – 1]
  • Print the value of arr[N].

Below is the implementation of the above approach: 

Java
// Dynamic Programming approach for
// Fibonacci series program in java

import java.io.*;

class fibonacci {

    // Function to find the fibonacci Series
    static int fib(int n)
    {

        // Declare an array to store
        // Fibonacci numbers.
        // 1 extra to handle case, n = 0
        int f[] = new int[n + 2];

        int i;

        // 0th and 1st number of
        // the series are 0 and 1
        f[0] = 0;
        f[1] = 1;

        for (i = 2; i <= n; i++) {

            // Add the previous 2 numbers
            // in the series and store it
            f[i] = f[i - 1] + f[i - 2];
        }

        // Nth Fibonacci Number
        return f[n];
    }

    public static void main(String args[])
    {
        // Given Number N
        int N = 10;

        // Print first 10 term
        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(N) 
Auxiliary Space: O(N)

To know more about the Fibonacci Series, refer to the article – Program to print first n Fibonacci Numbers.



Previous Article
Next Article

Similar Reads

Program to Print Fibonacci Series
Ever wondered about the cool math behind the Fibonacci series? This simple pattern has a remarkable presence in nature, from the arrangement of leaves on plants to the spirals of seashells. We're diving into this Fibonacci Series sequence. It's not just math, it's in art, nature, and more! Let's discover the secrets of the Fibonacci series together
9 min read
Java Program for nth multiple of a number in Fibonacci Series
Given two integers n and k. Find position the n'th multiple of K in the Fibonacci series. Examples: Input : k = 2, n = 3 Output : 9 3'rd multiple of 2 in Fibonacci Series is 34 which appears at position 9. Input : k = 4, n = 5 Output : 30 5'th multiple of 5 in Fibonacci Series is 832040 which appears at position 30. An Efficient Solution is based o
4 min read
Java Program to Find Sum of Fibonacci Series Numbers of First N Even Indexes
For a given positive integer N, the purpose is to find the value of F2 + F4 + F6 +………+ F2n till N number. Where Fi indicates the i'th Fibonacci number. The Fibonacci Series is the numbers in the below-given integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ……Examples: Input: n = 4 Output: 33 N = 4, So here the fibonacci series will be prod
4 min read
Print Fibonacci Series in reverse order
Given a number n then print n terms of fibonacci series in reverse order. Examples: Input : n = 5 Output : 3 2 1 1 0 Input : n = 8 Output : 13 8 5 3 2 1 1 0 Algorithm 1) Declare an array of size n. 2) Initialize a[0] and a[1] to 0 and 1 respectively. 3) Run a loop from 2 to n-1 and store sum of a[i-2] and a[i-1] in a[i]. 4) Print the array in the r
4 min read
Print Fibonacci Series in reverse order using Recursion
Given an integer N, the task is to print the first N terms of the Fibonacci series in reverse order using Recursion. Examples: Input: N = 5Output: 3 2 1 1 0Explanation: First five terms are - 0 1 1 2 3. Input: N = 10Output: 34 21 13 8 5 3 2 1 1 0 Approach: The idea is to use recursion in a way that keeps calling the same function again till N is gr
3 min read
Check if a M-th fibonacci number divides N-th fibonacci number
Given two numbers M and N, the task is to check if the M-th and N-th Fibonacci numbers perfectly divide each other or not.Examples: Input: M = 3, N = 6 Output: Yes F(3) = 2, F(6) = 8 and F(6) % F(3) = 0 Input: M = 2, N = 9 Output: Yes A naive approach will be to find the N-th and M-th Fibonacci numbers and check if they are perfectly divisible or n
8 min read
Check if sum of Fibonacci elements in an Array is a Fibonacci number or not
Given an array arr[] containing N elements, the task is to check if the sum of Fibonacci elements of the array is a fibonacci number or not.Examples: Input: arr[] = {2, 3, 7, 11} Output: Yes Explanation: As there are two Fibonacci numbers in the array i.e. 2 and 3. So, the sum of Fibonacci numbers is 2 + 3 = 5 and 5 is also a Fibonacci number. Inpu
7 min read
Program to print Fibonacci Triangle
Given the value of n(n < 10), i.e, number of lines, print the Fibonacci triangle. Examples: Input : n = 5 Output : 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 Input : n = 7 Output : 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 The Fibonacci numbers are the numbers in the fol
7 min read
Program to print first n Fibonacci Numbers | Set 1
Given an integer N. The task is to find the first N Fibonacci numbers. Examples :  Input: n = 3Output: 0 1 1 Input: n = 7Output: 0 1 1 2 3 5 8 Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.  Program to print first 'n' Fibonacci Numbers using recursion:Below is the idea to solve the problem: Use recursion to fin
7 min read
Factorial of each element in Fibonacci series
Given the upper limit, print factorials of all Fibonacci Numbers smaller than the limit.Examples : Input : limit = 20 Output : 1 1 1 2 6 120 40320 6227020800 Explanation : Fibonacci series in this range is 0, 1, 1, 2, 3, 5, 8, 13. Factorials of these numbers are output. Input : 50 Output : 1 1 1 2 6 120 40320 6227020800 51090942171709440000 2952327
11 min read
Find n terms of Fibonacci type series with given first two terms
Given first two numbers of series, find n terms of series with these two numbers. The given series follows the same concept as Fibonacci series, i.e., n-th term is sum of (n-1)-th and (n-2)-th terms. Examples: Input: first = 5, sec = 8, n = 5 Output: 5, 8, 13, 21, 34 Input: first = 2, sec = 4, n = 5 Output: 2, 4, 6, 10, 16 Approach: The approach is
7 min read
Sum of nth terms of Modified Fibonacci series made by every pair of two arrays
Given two arrays A and B of same size m. You have to find the sum of nth terms of Fibonacci like series (value of every term is sum of previous two terms) formed by every element of A as first and every element of B as second. Examples: Input : {1, 2, 3}, {4, 5, 6}, n = 3 Output : 63 Explanation : A[] = {1, 2, 3}; B[] = {4, 5, 6}; n = 3; All the po
9 min read
K- Fibonacci series
Given integers 'K' and 'N', the task is to find the Nth term of the K-Fibonacci series. In K - Fibonacci series, the first 'K' terms will be '1' and after that every ith term of the series will be the sum of previous 'K' elements in the same series. Examples: Input: N = 4, K = 2 Output: 3 The K-Fibonacci series for K=2 is 1, 1, 2, 3, ... And, the 4
7 min read
Find the Nth element of the modified Fibonacci series
Given two integers A and B which are the first two terms of the series and another integer N. The task is to find the Nth number using Fibonacci rule i.e. fib(i) = fib(i - 1) + fib(i - 2)Example: Input: A = 2, B = 3, N = 4 Output: 8 The series will be 2, 3, 5, 8, 13, 21, ... And the 4th element is 8.Input: A = 5, B = 7, N = 10 Output: 343 Approach:
5 min read
Nth term of a Custom Fibonacci series
Given three integers A, B and N. A Custom Fibonacci series is defined as F(x) = F(x - 1) + F(x + 1) where F(1) = A and F(2) = B. Now the task is to find the Nth term of this series.Examples: Input: A = 10, B = 17, N = 3 Output: 7 10, 17, 7, -10, -17, ...Input: A = 50, B = 12, N = 10 Output: -50 Approach: It can be observed that the series will go o
4 min read
Last digit of sum of numbers in the given range in the Fibonacci series
Given two non-negative integers M, N which signifies the range [M, N] where M ? N, the task is to find the last digit of the sum of FM + FM+1... + FN where FK is the Kth Fibonacci number in the Fibonacci series. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... Examples: Input: M = 3, N = 9 Output: 6 Explanation: We need to find F3 + F4 + F5 + F6 +
5 min read
Check whether Array represents a Fibonacci Series or not
Given an array arr[] consisting of N integers, the task is to check whether a Fibonacci series can be formed using all the array elements or not. If possible, print "Yes". Otherwise, print "No". Examples: Input: arr[] = { 8, 3, 5, 13 } Output: Yes Explanation: Rearrange given array as {3, 5, 8, 13} and these numbers form Fibonacci series. Input: ar
9 min read
Nth Term of a Fibonacci Series of Primes formed by concatenating pairs of Primes in a given range
Given two integers X and Y, the task is to perform the following operations: Find all prime numbers in the range [X, Y].Generate all numbers possible by combining every pair of primes in the given range.Find the prime numbers among all the possible numbers generated above. Calculate the count of primes among them, say N.Print the Nth term of a Fibo
13 min read
Sum of the first N terms of XOR Fibonacci series
Given three positive integers A, B, and N where A and B are the first two terms of the XOR Fibonacci series, the task is to find the sum of the first N terms of XOR Fibonacci series which is defined as follows: F(N) = F(N – 1) ^ F(N – 2) where ^ is the bitwise XOR and F(0) is 1 and F(1) is 2. Examples: Input: A = 0, B = 1, N = 3Output: 2Explanation
15+ min read
Minimize array elements required to be incremented or decremented to convert given array into a Fibonacci Series
Given an array arr[], the task is to find the minimum number increments or decrements by 1 required to convert the array into a Fibonacci Series. If it is not possible, then print -1. Note: Each array element can be incremented or decremented only once. Examples: Input: arr[] = {4, 8, 9, 17, 21}Output: 3Explanation:The array can be converted into a
8 min read
n'th multiple of a number in Fibonacci Series
Given two integers n and k. Find position the n'th multiple of K in the Fibonacci series. Examples : Input : k = 2, n = 3 Output : 9 3'rd multiple of 2 in Fibonacci Series is 34 which appears at position 9. Input : k = 4, n = 5 Output : 30 4'th multiple of 5 in Fibonacci Series is 832040 which appears at position 30. Recommended: Please solve it on
7 min read
Java Program for Print Number series without using any loop
Givens Two number N and b, our task is to subtract a number K from N until number(N) is greater than zero, once the N becomes negative or zero then we start adding K until that number becomes the original number(N). Remember: Here we are not allow to use any loop. Examples : Input : N = 15 K = 5 Output : 15 10 5 0 1 5 10 15 Input : N = 20 K = 6 Out
2 min read
Java Program for n-th Fibonacci numbers
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Fn = Fn-1 + Fn-2with seed values F0 = 0 and F1 = 1.Method 1 ( Use recursion ) Java Code // Fibonacci Series using Recursion class Fibonacci { static int fib(int n) { if (n==0) return 0; else if(n==1 || n==2) return 1; return fib(n - 1) + fib(n - 2); }
4 min read
Java Program for Zeckendorf\'s Theorem (Non-Neighbouring Fibonacci Representation)
Given a number, find a representation of number as sum of non-consecutive Fibonacci numbers. Examples: Input: n = 10 Output: 8 2 8 and 2 are two non-consecutive Fibonacci Numbers and sum of them is 10. Input: n = 30 Output: 21 8 1 21, 8 and 1 are non-consecutive Fibonacci Numbers and sum of them is 30. The idea is to use Greedy Algorithm. 1) Let n
2 min read
Java Program for How to check if a given number is Fibonacci number?
Given a number 'n', how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, .. Examples : Input : 8 Output : Yes Input : 34 Output : Yes Input : 41 Output : No Following is an interesting property about Fibonacci numbers that can also be used to check if a given number is Fibonacci or n
2 min read
Print first n Fibonacci Numbers using direct formula
Given a number n, the task is to print first n Fibonacci numbers. Prerequisite: Program to print first n Fibonacci Numbers | Set 1 Examples: Input : 7 Output :0 1 1 2 3 5 8 Input : 5 Output :0 1 1 2 3 N-th Fibonacci Number = [(1 + ?5)n - (1 - ?5)n)] / [2n * ?5] Below is the implementation. C/C++ Code // C++ code to print fibonacci // numbers till n
4 min read
Print Fibonacci sequence using 2 variables
Print the Fibonacci sequence. The first Fibonacci numbers are: C/C++ Code // Simple CPP Program to print Fibonacci // sequence #include <iostream> using std::cout; void fib(int n) { int a = 0, b = 1, c; if (n >= 0) cout << a << " "; if (n >= 1) cout << b << " "; for (int i = 2; i <= n; i++)
6 min read
Program to print triangular number series till n
A triangular number or triangle number counts objects arranged in an equilateral triangle, as in the diagram on the right. The n-th triangular number is the number of dots composing a triangle with n dots on a side, and is equal to the sum of the n natural numbers from 1 to n. Examples : Input : 5 Output : 1 3 6 10 15 Input : 10 Output : 1 3 6 10 1
8 min read
Program to print binomial expansion series
Given three integers, A, X and n, the task is to print terms of below binomial expression series. (A+X)n = nC0AnX0 + nC1An-1X1 + nC2An-2X2 +....+ nCnA0Xn Examples: Input : A = 1, X = 1, n = 5 Output : 1 5 10 10 5 1 Input : A = 1, B = 2, n = 6 Output : 1 12 60 160 240 192 64 Simple Solution : We know that for each value of n there will be (n+1) term
12 min read
Program to print the Sum of series -1 + 2 + 11 + 26 + 47 +.....
Given a number N, the task is to find the sum of first N number of series: -1, 2, 11, 26, 47, 74, ..... Examples: Input: N = 3 Output: 12 Explanation: Sum = (N * (N + 1) * (2 * N - 5) + 4 * N) / 2 = (3 * (3 + 1) * (2 * 3 - 5) + 4 * 3) / 2 = 12 Input: N = 9 Output: 603 Approach:The Nth term of the given series can be generalised as:Nth term of the s
4 min read
three90RightbarBannerImg