September 18th, 2002, 04:56 PM
addition / recursion problem
If you wanted to add all numbers together from 1 to x (ex. 1+2+3+4+5...x) what is the best way? Mathmatically there are ways easier than adding them all up in order, but I am curious about the programming side. Are there better ways to do this problem besides the obvious answers of a) one loop that takes forever or b) the recursion solution?
September 18th, 2002, 06:01 PM
Not that you should listen to me (I seem to have a problem with Basic Algebra), but I think this will work:
((n + 1) / 2) * ((n - 1) + 1)
((n + 1) / 2) * n
Incidentally, this should work for a consecutive series between any two numbers. Just replace the inner 1's with the smaller number. For example:
To add the series 4+5+6+7+8+9+10, the equation would be:
((10+4) / 2) * ((10 - 4) + 1)
Which should equal 49...the same answer to 4+5+6+7+8+9+10. Again, I think this will always work, but I'm not sure.
The algebraic equation to add all numbers between x and n:
((n + x) / 2) * ((n - x) + 1)
/* You are not expected to understand this. */