Add a sequence of numbers recursively

Hey, I'm trying to refresh my mind with a little recursion. I want to add all numbers from "start" to "end" inclusive.

Ie, if the beginning was 1 and the end was 5. Then the answer would be 1 + 2 + 3 + 4 + 5 = 15

As long as I have this

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

Doesn't work (I get a seg fault). What am I doing wrong?

EDIT: Sorry that I use the same variables in my actual code when I wrote this and in the end I told them how to start / end and forgot to change the whole code.

+6
source share
4 answers

What are the from and to variables inside your function? Perhaps you are using some globals instead of using start and end and why do you have a problem? Also why are you using sum1 inside 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); } 
+7
source

Firstly, you do not use your functional parameters (start, end) that you use (from, to). I assume that from and to either global variables or your code will not compile. Also, where is the general announcement announced?

This should work better:

 int calc(int start, int end){ if(start > end) return 0; else{ return start + calc(start+1, end); } } 
+3
source

By the way, here is 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); } 

This is even recursive! Well, until you simplify it further

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

This is because f (n) = n + ... + 3 + 2 + 1 = n (n + 1) / 2

+3
source

This works great.

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

Source: https://habr.com/ru/post/887589/


All Articles