Write a Java program to check if a given number is Fibonacci number or not


This Java program checks if a given number entered by the user is a Fibonacci number. It defines two helper functions: is_perfect_square() and isfibonacci().

  • The is_perfect_square() function takes an integer n and checks if it is a perfect square by computing its square root using the Math.sqrt() function and then checking if the square of the integer part of the square root is equal to n.
  • The isfibonacci() function takes an integer n and checks if it is a Fibonacci number by computing 5*n*n + 4 and 5*n*n - 4 and checking if either of them is a perfect square using the is_perfect_square() function.
  • In the main() function, the program takes an integer input from the user using the Scanner class and calls the isfibonacci() function to check if the number is a Fibonacci number. If the number is greater than 0, the program displays the result. If the number is less than or equal to 0, the program does not display anything.

Overall, this program checks if a given number is a Fibonacci number by calling the isfibonacci() function and displays the result.

Source Code

import java.util.*;
class Fibonacci
{
	static boolean is_perfect_square(int n)
	{
		int sq = (int) Math.sqrt(n);
		return (sq*sq == n);
	}
	static boolean isfibonacci(int n)
	{
		return is_perfect_square(5*n*n + 4) || is_perfect_square(5*n*n - 4);
	}
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter the Number : ");
		int num = input.nextInt();
		if (num > 0)
		{
			System.out.println("Is Fibonacci Number ? "+isfibonacci(num));
		}
	}
}

Output

Enter the Number : 5
Is Fibonacci Number ? true

Enter the Number : 10
Is Fibonacci Number ? false

Example Programs