fibonacci series - recursive summation

前端 未结 6 1347
天命终不由人
天命终不由人 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:32

    No it won't. The second version of the code does not compute the sum of all the values of the fibonacci function up to the given value. And the base cases are wrong, too!

    If you want to calculate the sum recursively, split the problem in two parts, like this:

    public static int fib(int n) {
        return n < 2 ? n : fib(n-1) + fib(n-2);
    }
    
    public static int sumfib(int n) {
        return n < 0 ? 0 : fib(n) + sumfib(n-1);
    }
    

    The first function calculates fibonacci, the second takes care of adding the values up to a given number.

提交回复
热议问题