Test if a number is fibonacci

后端 未结 20 939
深忆病人
深忆病人 2020-11-30 17:58

I know how to make the list of the Fibonacci numbers, but i don\'t know how can i test if a given number belongs to the fibonacci list - one way that comes in mind is genera

20条回答
  •  半阙折子戏
    2020-11-30 18:38

    int isfib(int n /* number */, int &pos /* position */)
    {
       if (n == 1)
       {
          pos=2;  // 1 1
          return 1;
       }
       else if (n == 2)
       {
          pos=3;  // 1 1 2
          return 1;
       }
       else
       {
          int m = n /2;
          int p, q, x, y;
          int t1=0, t2 =0;
          for (int i = m; i < n; i++)
          {
            p = i;
            q = n -p;    // p + q = n
            t1 = isfib(p, x);
            if (t1) t2 = isfib(q, y);
            if (t1 && t2 && x == y +1)
            {
               pos = x+1;
               return 1; //true
            }
          }
          pos = -1;
          return 0; //false
       }
    }
    

    How about this?

提交回复
热议问题