Recursively add sequence of numbers

北城余情 提交于 2019-12-22 05:36:10

问题


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.


回答1:


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);
} 



回答2:


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);
    }
} 



回答3:


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




回答4:


This works fine for.

int calc(int from, int to)
{
    if (from >= to) return to;
    return from + calc(from + 1, to); 
}


来源:https://stackoverflow.com/questions/5932380/recursively-add-sequence-of-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!