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.
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);
}
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);
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With