Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

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 (y-x+1)/2*(x+y);}`
So if for example you call sumRange(11,10000) which returns 50004945 which is what you get when you add 11+12+13+14+...+9999+10000 together

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.

2. 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

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•