Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum all integers below a given integer using recursion

Right off the bat, this is NOT a homework question. I am practicing recursion problems in my free time and I am still wrapping my head around the concept. I am super close to solving this one, but I can't figure out how to skip the root integer 'n' when I am summing them together. Here is the code so far:

var sumBelow = function (n) {
    console.log(n);
    // base case
    if (n === 0) {
        console.log('we hit the base case');
        return 0;
    }
    // initialize var to hold sum
    if (!sum_sumBelow) var sum_sumBelow = 0;
    // add numbers
    sum_sumBelow = n + sumBelow(n - 1);
    return sum_sumBelow;
};

console.log('answer is', sumBelow(4));

When I call 'sumBelow(4)' what I want is 3+2+1, but I am currently getting 4+3+2+1.

How do I skip the root parameter???

like image 414
Angela Yu Avatar asked Jan 19 '26 17:01

Angela Yu


1 Answers

Assuming you are printing everything correctly what is wrong with just changing:

sum_sumBelow = n + sumBelow(n - 1);

to

sum_sumBelow = n - 1 + sumBelow(n - 1);

In your example; answer is 6 would be outputted in the console which is 3 + 2 + 1 as you want?

N.B. By no means is this the best recursive solution but it still is one.

Here is an equivalent of your whole function provided by @RobG which uses a ternary:

function sumBelow(n) {return n ? n-1 + sumBelow(n-1) : 0}
like image 168
Sash Sinha Avatar answered Jan 21 '26 08:01

Sash Sinha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!