Follow @devglan
Java Program to test if a given number is Fibonacci or not
Description
Fibonacci numbers are the numbers in which each number is the sum of the two preceding numbers.For example 1, 1, 2, 3, 5, 8, 13, 21, 34, ...The first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence.In most of the java interview, itapos;s a common programming question to check a given number is fibonacci number or not.Following is the program to check the same on the basis of wiki - Alternatively, a positive integer z is a Fibonacci number if and only if one of 5z^2 + 4 or 5z^2 ? 4 is a perfect square
FibonacciNumber.javapackage com.devglan; public class FibonacciNumber { public static boolean isPerfectSquare(int x) { int s = (int) Math.sqrt(x); return (s*s == x); } public static boolean isFibonacci(int n) { return isPerfectSquare(5*n*n + 4) || isPerfectSquare(5*n*n - 4); } public static void main(String[] args) { int[] array = {8, 16, 34}; for(int i = 0; i < array.length; i++){ if(isFibonacci(array[i])){ System.out.println(array[i] + " is a fibonacci number."); }else { System.out.println(array[i] + " is not a fibonacci number."); } } } }
Explanation
Click to Suggest Your Own Explanation
A positive integer z is a Fibonacci number if and only if one of 5z^2 + 4 or 5z^2 ? 4 is a perfect square.
Other Similar Java Programs:
If You Appreciate This, You Can Consider:
- Share this article on social media or with your teammates.