Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively add sequence of numbers

Hey im trying to refresh my mind with a bit of recursion. I want to add all numbers from 'start' to 'end' inclusive.

I.e if start was 1, and end was 5. Then the answer would be 1+2+3+4+5 = 15

So far I've got this

int calc(int start, int end){
    if(start > end)
        return total;
    else{
        total = total + start;  
    return sum1(start++, end);
    }
} 

Its not working (i get seg fault). What am i doing wrong?

EDIT: Sorry i am using the same variables in my actual code, when i wrote this i ended up reffering to them as start/end and forgot to change all the code.

like image 641
Sean Avatar asked May 09 '11 04:05

Sean


3 Answers

What are from and to variables inside your function? Maybe you use some globals instead of using start and end and that's why you have the problem? Also why are you using sum1 inside the calc function instead of calc?

Try this instead:

int calc(int start, int end){
    if(start > end)
        return 0;
    else
        return start + calc(start + 1, end);
} 
like image 164
insumity Avatar answered Nov 14 '22 09:11

insumity


For starters, you aren't using your function parameters (start, end), you are using (from, to) instead. I assume from and to are either global variables or your code wouldn't compile. Furthermore, where is total declared?

This should work better:

int calc(int start, int end){
    if(start > end)
        return 0;
    else{
        return start + calc(start+1, end);
    }
} 
like image 28
GWW Avatar answered Nov 14 '22 09:11

GWW


By the way, here's a more efficient solution:

int calc(int from, int to)
{
    if (from == 0)
        return to * (to+1) / 2;
    else
        return calc(0, to) - calc(0, from);
}

It's even recursive! Well, until you simplify it further to

int calc(int from, int to)
{
    return ( to * (to+1) - from * (from+1) ) / 2;
}

That's because f(n) = n+...+3+2+1 = n(n+1)/2

like image 3
ikegami Avatar answered Nov 14 '22 07:11

ikegami