Determining whether a number is a Fibonacci number

前端 未结 14 1198
暗喜
暗喜 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:17

    //Program begins
    
    
    public class isANumberFibonacci {
    
        public static int fibonacci(int seriesLength) {
            if (seriesLength == 1 || seriesLength == 2) {
                return 1;
            } else {
                return fibonacci(seriesLength - 1) + fibonacci(seriesLength - 2);
            }
        }
    
        public static void main(String args[]) {
            int number = 4101;
            int i = 1;
            while (i > 0) {
                int fibnumber = fibonacci(i);
                if (fibnumber != number) {
                    if (fibnumber > number) {
                        System.out.println("Not fib");
                        break;
                    } else {
                        i++;
                    }
                } else {
                    System.out.println("The number is fibonacci");
                    break;
                }
            }
        }
    }
    
    //Program ends
    

提交回复
热议问题