Test if a number is fibonacci

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

    Re: Ahmad's code - a simpler approach with no recursion or pointers, fairly naive, but requires next to no computational power for anything short of really titanic numbers (roughly 2N additions to verify the Nth fib number, which on a modern machine will take milliseconds at worst)

    // returns pos if it finds anything, 0 if it doesn't (C/C++ treats any value !=0 as true, so same end result)

    int isFib (long n)
    {
        int pos = 2;
        long last = 1;
        long current = 1;
        long temp;
    
        while (current < n)
        {
            temp = last;
            last = current;
            current = current + temp;
            pos++;
        }
    
        if (current == n)
            return pos;
        else
            return 0;
    
    }
    

提交回复
热议问题