Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Sydney, Australia
    Thanked 932 Times in 919 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.

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

  2. #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    London, England
    Thanked 2,700 Times in 2,676 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.


Posting Permissions

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