Check whether given number is fibonacci


Given a number check whether it is fibonacci or not

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, ..

Input: 8
Output: Yes

Input: 41
Output: No

Fibonacci numbers have a property that either 5n^2 +4 or 5n^2 - 4 is a perfect square.

Code:

import java.util.*;

public class Solution {

    static boolean isFibonacci(int n) {
        int check1 = 5*n*n + 4;
        int check2 = 5*n*n - 4;
        boolean fib = false;
        
        
        int sqt = (int)Math.sqrt(check1);
        int square = sqt * sqt;
        
        if(square == check1){
            fib = true;
        }
        
        sqt = (int)Math.sqrt(check2);
        square = sqt * sqt;
         
        if(square == check2){
            fib = true;
        }
        
        return fib;
}

    public static void main(String[] args) {
        System.out.println("fibonacci between 2 to 50:");
        for(int i=2; i<=50; i++){
            if(isFibonacci(i)){
                System.out.println(i);
            }
        }
        
        
}
}

Output:

fibonacci between 2 to 50:
2
3
5
8
13
21
34

Comments

Popular posts from this blog

Rearrange Array in Maximum-Minimum form

Find Maximum in Binary Tree