Recursively add sequence of numbers

我们两清 提交于 2019-12-05 05:57:30

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

This works fine for.

int calc(int from, int to)
{
    if (from >= to) return to;
    return from + calc(from + 1, to); 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!