Java Program to test if a given number is Fibonacci or not

Java Program to test if a given number is Fibonacci or not thumbnail
12K
By Dhiraj Ray 31 December, 2017

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.java
package 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

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.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.