Determining whether a number is a Fibonacci number

前端 未结 14 1386
暗喜
暗喜 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

    I don't know if there is an actual formula that you can apply to the user input however, you can generate the fibonacci sequence and check it against the user input until it has become smaller than the last number generated.

    int userInput = n;
    int a = 1, b = 1;
    
    while (a < n) {
      if (a == n)
        return true;
    
      int next = a + b;
      b = a;
      a = next;
    }
    
    return false;
    

提交回复
热议问题