Enjoy an ad free experience by logging in. Not a member yet? Register.

Results 1 to 2 of 2
Thread: Adding sequential numbers

03052014, 01:52 AM #1
 Join Date
 Sep 2005
 Location
 Sydney, Australia
 Posts
 6,631
 Thanks
 0
 Thanked 648 Times in 638 Posts
Adding sequential numbers
I came across an interesting JavaScript homework question just recently where the person was asking which type of loop was best used for the solution.
The question was to accept two integers and then add all of the integers between them (inclusive) together and display the result. (eg. 3 and 6 returns 18)
Of course the correct answer is that the solution to this question doesn't require a loop at all.
Assuming that x<=y the following function calculates the answer without actually adding up all the separate numbers.
Code:sumRange = function(x, y) {return (yx+1)/2*(x+y);}
For any calculations where there are patterns to the numbers (in this case the numbers being sequential integers) there is always a formula that can be applied so as to avoid the need for a loop.
Probably the most common place where calculations involving sequential integers occurs is with dates.Stephen
Learn Modern JavaScript  http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/
Don't forget to start your JavaScript code with"use strict";
which makes it easier to find errors in your code.
03072014, 11:57 AM
#2
 Join Date
 Jun 2002
 Location
 London, England
 Posts
 17,922
 Thanks
 203
 Thanked 2,531 Times in 2,509 Posts
Yes, there are many calculations which can be performed without using a loop, which is not to say that loops should somehow be avoided in all situations. Other similar examples:
Sum of even numbers:
Formula: N(N+1)
Where N = (First Even + Last Even)/2  1
Example: 2+4+6+ ....... 100
N = (2+100)/2  1 = 50
Sum of first 50 positive even integers = 50*51 = 2550
Sum of odd numbers:
If N = number of odd terms then sum = N^2
1+3+5+7 = 4^2 = 16
All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.