C++, Write a recursive function “Summation” that takes two integer numbers n and m and it returns the summation of all the numbers between n and m. If n > m the function returns zero. Examples: Summation(3, 7) = 3 + 4 + 5 + 6 + 7 = 25 Summation(7, 2) = 0 Summation(4,4) = 4 Summation(-3,1) = -5
what grade is this (I'm in 6th).
im not going to school
are you on flvs?
nope ;p
o.o ?
@ganeshie8
can you help me with the problem plz
ask Pooja 195.
Thanks
@pooja195
I don't know this stuff sorry! ;-;
I see its ok
... sorry.
np
okay so basically
Summation(3, 7) this 7 has to keep going down by 1 until 3 for each recursion
What type of math is this???
int sum(int n,int m) { if ( n>m) return 0; else{ return n+sum(n,m-1); } } int main() { cout << sum(3,7); }
closest I could come up with
return m+sum(n,m-1); ?
results got better but still
oh wait it worked
How did you find out lol
If you return n+sum(n,m-1), you just keep adding n for (n-m+1) times.
one more try ;)
sum(a,b) if b>a return b+sum(a,b-1) else return 0
sum(a,b) if b>a return a+sum(a+1,b) else return 0
this is okay too if u want to count up in each recursion its more natural
since thats how ur question is stated
\[S_n = a_n + S_{n-1}\]
int sum(int n,int m) { if ( n>m) return 0; else{ return n+sum(n,m-1); } } sum (n,m) = n+sum(n,m-1) = n + (n + sum (n, m-2)) = 2n + sum(n, m-2) = 2n + (n + sum (n, m-3)) = 3n + sum (n, m-3) = ... = kn + (n + sum(n, m-(k+1)) = (k+1)n + sum(n, m-(k+1)) = ... Until m = n, we have = (n-1)n + (n + sum(n, m-n) = n*n + sum (n, m-n) = n*n + (n) + sum(n, m-(n+1)) = (n+1)n + 0 = (n+1)n So, you add n for n+1 times. Right? Still wrong?
Hey, I think counting up or counting down doesn't really matter. Both ways work. My concern is, how many times you added "n" in the asker's solution.
|dw:1448640402925:dw|
Join our real-time social learning platform and learn together with your friends!