Java Program for check if a given number is Fibonacci number?

JavaObject Oriented ProgrammingProgramming

Following is the Java program to check if a given number is Fibonacci −

Example

 Live Demo

public class Demo{
   static boolean perfect_square_check(int val){
      int s = (int) Math.sqrt(val);
      return (s*s == val);
   }
   static boolean fibonacci_num_check(int n){
      return perfect_square_check(5*n*n + 4) || perfect_square_check(5*n*n - 4);
   }
   public static void main(String[] args){
      for (int i = 6; i <= 17; i++)
      System.out.println(fibonacci_num_check(i) ? i + " is a Fibonacci number" :
      i + " is a not Fibonacci number");
   }
}

Output

6 is a not Fibonacci number
7 is a not Fibonacci number
8 is a Fibonacci number
9 is a not Fibonacci number
10 is a not Fibonacci number
11 is a not Fibonacci number
12 is a not Fibonacci number
13 is a Fibonacci number
14 is a not Fibonacci number
15 is a not Fibonacci number
16 is a not Fibonacci number
17 is a not Fibonacci number

A class named Demo defines a static Boolean function that takes in an integer value as parameter. It checks the square root of the value and assigns it to another value. If the product of square root multiplied by square root is equal to the value passed, then it is returned.

Next, another Boolean static function is defined that calls the previous function. In the main function, the starting number, and the ending number are iterated through, and relevant message is printed as well as checking whether every number is a Fibonacci number or not.

raja
Published on 04-Jul-2020 10:42:09
Advertisements