Reputation: 31
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
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