Determining whether a number is a Fibonacci number

前端 未结 14 1383
暗喜
暗喜 2021-01-18 05:35

I need to to write a Java code that checks whether the user inputed number is in the Fibonacci sequence.

I have no issue writing the Fibonacci sequence to output, b

14条回答
  •  别那么骄傲
    2021-01-18 06:27

    Finding out whether a number is Fibonacci based on formula:

    public static boolean isNumberFromFibonacciSequence(int num){
    
        if (num == 0 || num == 1){
            return true;
        }
    
        else {
            //5n^2 - 4 OR 5n^2 + 4 should be perfect squares
            return isPerfectSquare( 5*num*num - 4) || isPerfectSquare(5*num*num - 4);
        }
    }
    
    private static boolean isPerfectSquare(int num){
            double sqrt = Math.sqrt(num);
            return sqrt * sqrt == num;
    }
    

提交回复
热议问题