Write a JavaScript program to add all numbers in between any two given numbers.
Easiest way is to use the mathematical formula
1+2+...+n = n(n+1)/2
Here you want the sum,
m+(m+1)+...+n
Example code of Sum all numbers between two integers in JavaScript
Here is HTML example code to add all number between range including given numbers.
<!DOCTYPE html>
<html>
<body>
<script>
function sumSeries (first, last) {
var n = (last - first + 1)
var sum = n * (first + last) / 2;
return sum;
}
var sum = sumSeries(1, 10);
console.log(sum);
</script>
</body>
</html>
Output:
Optimum algorithm
JavaScript example return sum all numbers in a range.
function sumAll(min, max) {
return ((max-min)+1) * (min + max) / 2;
}
Do comment if you have any doubts and suggestion on this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version