crisscross
crisscross

Reputation: 31

Write a function sumRange, which, when given two integers FROM and TO, returns the sum of integers from FROM to TO

Could anyone please tell me how I could write this code better, I'm having a bit of trouble getting mine to work

function sumRange(from, to) {
      var f = from;
      var t = to;
      var result = from;
      if(to >= from) {
        while (to > from) {
          from ++;
          result += from;
        }
        return result;
      } else if (from > to) {
        result = to;
        while (from > to ) {
          to++;
          result += to;
        }
        return result;
      }

    }

Upvotes: 1

Views: 57

Answers (1)

jspcal
jspcal

Reputation: 51914

The sum of the integers between a and b is:

((b - a + 1) * (a + b)) / 2

See http://mathworld.wolfram.com/ArithmeticSeries.html

To handle the arguments in any order:

function sumRange(a, b) {
    return ((Math.abs(b - a) + 1) * (a + b)) / 2;
}

Upvotes: 3

Related Questions