Home / Programs / check if a number is a Fibonacci number in Java
🚀 Programming Example

check if a number is a Fibonacci number in Java

👁 195 Views
💻 Practical Program
📘 Step Learning

To check if a number is a Fibonacci number in Java, you can follow a methodical approach based on the properties of Fibonacci sequence. Here's how you can implement it:

📌 Information & Algorithm

  • 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 Code

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.");
        }
    }
}

                        

🖥 Program 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.
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.