Recursive Fibonacci Function (With Negative Numbers)

点点圈 提交于 2020-01-06 09:10:08

问题


I am able to write a recursive Fibonacci function for all numbers greater than 0, but the function is completely incorrect for anything negative. Any idea how to implement this in c++?

int fibonacci(int n){
    if(n == 0)return 0;
    if(n == 1)return 1;

    return fibonacci(n - 1) + fibonacci(n - 2);
}

回答1:


According to wikipedia, http://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers, the recursive function for negative numbers is different than for possitive numbers.

For possitive: n_2 = n_1 + n_0

For negative: n_-2 = n_-1 - n_0

So that the recursivity works "just the other way around" and the same code will not work. You will have to write a new function.

EDIT: Wikipedia provides the generalization: F_-n = (-1)^n F_n so just compute F_n and modify the sign with (-1)^n




回答2:


A bit late on this thread however here is my 2 cents on the issue.

As shown on the wikipedia entry, Fibonacci can be bidirectional. In order to implement it in PHP you need to first check if the inbound parameter is negative so you know how to handle it later on as it does require a different formula to handle the negatives.

Take note that the negative side of Fibonacci numbers do not always yield a negative value.

The formula for bi-directional is:

F-n = (-1)n+1 x Fn;

Fibonacci requires seeding for 0 and 1 and when implementing the bi-directional Fibonacci you also need to account for -1 as shown in the 2 exit points.

-----------------------------------------------------------------------
F−6 | F−5 | F−4 | F−3 | F−2 | F−1 | F0 | F1 | F2 | F3 | F4 | F5 | F6
----+-----+-----+-----+-----+-----+----+----+----+----+----+----+------
−8  |  5  |  −3 |  2  | −1  |  1  |  0 |  1 |  1 |  2 |  3 |  5 | 8
-----------------------------------------------------------------------

Below is my variation of the Fibonacci to handle negatives;

function negaFibonacci($n) 
{   

    // seed+exit
    if(($n == 1) || ($n == -1))
    {
        return 1;
    }   
    // seed+exit
    if($n == 0)
    {
        return 0;
    }    

    if($n < 0)
    {
        //https://en.wikipedia.org/wiki/Fibonacci_number#Negafibonacci
        return pow(-1,$n+1) * negaFibonacci(abs($n));
    } 
    else
    {
        //standard fib calc
        return negaFibonacci($n - 1) + negaFibonacci($n - 2);
    }


}

The function can be improved further with the rounding function but I have left it as is for readability.




回答3:


Here's how I would do it, I guess:

int fibonacci(int n){
    if (n < 0)
        return fibonacci(n * -1) * -1;
    if (n == 0) || (n == 1)
        return n;
    else
        return fibonacci(n - 1) + fibonacci(n - 2);
}


来源:https://stackoverflow.com/questions/25858498/recursive-fibonacci-function-with-negative-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!