How to check if a given number is Fibonacci number ? | Java program to check if x is a perfect square ; A utility method that returns true if x is perfect square ; Returns true if n is a Fibonacci Number , else false ; n is Fibonacci if one of 5 * n * n + 4 or 5 * n * n - 4 or both is a perfect square ; Driver method
class GFG { static boolean isPerfectSquare ( int x ) { int s = ( int ) Math . sqrt ( x ) ; return ( s * s == x ) ; } static boolean isFibonacci ( int n ) { return isPerfectSquare ( 5 * n * n + 4 ) || isPerfectSquare ( 5 * n * n - 4 ) ; } public static void main ( String [ ] args ) { for ( int i = 1 ; i <= 10 ; i ++ ) System . out . println ( isFibonacci ( i ) ? i + " ▁ is ▁ a ▁ Fibonacci ▁ Number " : i + " ▁ is ▁ a ▁ not ▁ Fibonacci ▁ Number " ) ; } }