check if a number is a Fibonacci number in Java

Mathematics for Programming Numbers (Article) Numbers (Program)

28

  • Understanding Fibonacci Numbers: Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the previous two. For example, the sequence begins: 0, 1, 1, 2, 3, 5, 8, 13, ...

  • Steps to Check for Fibonacci Numbers:

    • Determine if the number belongs to the Fibonacci sequence.
    • One way to check is to iterate through Fibonacci numbers until you find a number greater than or equal to the given number. If it matches the given number, then it's a Fibonacci number.

Given Input:

13

Expected Output:

13 is a Fibonacci number.

Program:

public class FibonacciChecker {
    public static boolean isPerfectSquare(int x) {
        int s = (int) Math.sqrt(x);
        return s * s == x;
    }
    
    public static boolean isFibonacci(int number) {
        // A number is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both is a perfect square
        return isPerfectSquare(5 * number * number + 4) || isPerfectSquare(5 * number * number - 4);
    }
    
    public static void main(String[] args) {
        int number = 13; // Example number to check
        
        if (isFibonacci(number)) {
            System.out.println(number + " is a Fibonacci number.");
        } else {
            System.out.println(number + " is not a Fibonacci number.");
        }
    }
}

Output:

13 is a Fibonacci number.

Explanation:

  • isPerfectSquare(int x) method checks if x is a perfect square by computing its square root and squaring it again to verify.
  • isFibonacci(int number) method checks if number is a Fibonacci number using a mathematical property that a number n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 is a perfect square.
  • In the main method, you can change the value of number to test different numbers for the Fibonacci property.

This Particular section is dedicated to Programs only. If you want learn more about Mathematics for Programming. Then you can visit below links to get more depth on this subject.