Test if a number is fibonacci

后端 未结 20 949
深忆病人
深忆病人 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:25

    Based on earlier answers by me and psmears, I've written this C# code.

    It goes through the steps slowly, and it can clearly be reduced and optimized:

    // Input: T: number to test.
    // Output: idx: index of the number in the Fibonacci sequence.
    //    eg: idx for 8 is 6. (0, 1, 1, 2, 3, 5, 8)
    // Return value: True if Fibonacci, False otherwise.
    static bool IsFib(long T, out int idx)
    {
        double root5 = Math.Sqrt(5);
        double PSI = (1 + root5) / 2;
    
        // For reference, IsFib(72723460248141) should show it is the 68th Fibonacci number
    
        double a;
    
        a = T*root5;
        a = Math.Log(a) / Math.Log(PSI);
        a += 0.5;
        a = Math.Floor(a);
        idx = (Int32)a;
    
        long u = (long)Math.Floor(Math.Pow(PSI, a)/root5 + 0.5);
    
        if (u == T)
        {
            return true;
        }
        else
        {
            idx = 0;
            return false;
        }
    }
    

    Testing reveals this works for the first 69 Fibonacci numbers, but breaks down for the 70th.

    F(69) = 117,669,030,460,994 - Works
    F(70) = 190,392,490,709,135 - Fails
    

    In all, unless you're using a BigInt library of some kind, it is probably better to have a simple lookup table of the Fibonacci Numbers and check that, rather than run an algorithm.

    A list of the first 300 Numbers is readily available online.

    But this code does outline a workable algorithm, provided you have enough precision, and don't overflow your number representation system.

提交回复
热议问题