Check whether a number is Fibonacci or not in Java

In this tutorial, we will see how to determine whether a number is a Fibonacci number or not in Java programming language.

We can verify if a number n is a Fibonacci number by checking if either (5*n^2 + 4) or (5*n^2 – 4) is a perfect square.
Here, we are using isPerfectsq function to check if the number n is a perfect square, and isfibonacci function is used to check if a given number n is a Fibonacci number. It checks whether (5*n^2 + 4) or (5*n^2 – 4)  is a perfect square or not using isPerfectsq method. If either of the numbers is a perfect square, then n is considered to be a Fibonacci number.

Let’s see an example for a better understanding of code.

public class is_Fibonacci {

    // function to determines whether a given number is a perfect square
    static boolean isPerfectSq(int x) {
        int s = (int) Math.sqrt(x);
        return s * s == x;
    }

    // Function to determine whether a number is fibonacci or not
    static boolean isfibonacci(int n) {
        // if (5 * n^2 + 4) or (5 * n^2 - 4) is a perfect square then it is a fibonacci number
        return isPerfectSq(5 * n * n - 4) || isPerfectSq(5 * n * n + 4);
    }

    public static void main(String[] args) {
        int number = 13; // number you want to check
        if (isfibonacci(number)) {
            System.out.println(number + " is in Fibonacci series. Hence, " + number + " is a Fibonacci number.");
        } else {
            System.out.println(number + " is not in Fibonacci Series. Hence, " + number + " is not a Fibonacci number.");
        }
    }
}

OUTPUT:

13 is in Fibonacci series. Hence, 13 is a Fibonacci number.

Leave a Reply

Your email address will not be published. Required fields are marked *