Determining whether a number is a Fibonacci number

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

    Thought it was simple until i had to rack my head on it a few minutes. Its quite different from generating a fibonacci sequence. This function returns 1 if is Fibonnaci or 0 if not

    public static int isFibonacci (int n){
      int isFib = 0;
      int a = 0, b = 0, c = a + b; // set up the initial values
      do 
       {
        a = b;
        b = c;
        c = a + b;
        if (c == n)
        isFib = 1;
        } while (c<=n && isFin == 0)
      return isFib;
    }
    
    public static void main(String [] args){
      System.out.println(isFibonacci(89));
    }
    

提交回复
热议问题