fibonacci series - recursive summation

前端 未结 6 1321
天命终不由人
天命终不由人 2021-02-09 14:45

Ok, I initially wrote a simple code to return the Fibonacci number from the series based on the user input..

n=5 will produce 3..

static int fibonacci(in         


        
6条回答
  •  甜味超标
    2021-02-09 15:26

    The right way to do it is use accumlator.

    the code should look something like this (i didn't check it, it's only the idea)

    static int fibonacci(int n, int accumlator) {
        if (n == 1)
            return 0;
        else if (n == 2)
            return 1;
        else
            accumlator = (fibonacci(n - 1, accumlator) + fibonacci(n - 2, accumlator));
            return accumlator;
    }
    

提交回复
热议问题