Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sum of even numbers from n to m regardless if nm JavaScript
We are required to write a function that takes two numbers as arguments m and n, and it returns the sum of all even numbers that falls between m and n (both inclusive).
For example:
If m = 10 and n = -4
The output should be 10+8+6+4+2+0+(-2)+(-4) = 24
Approach
We will first calculate the sum of all even numbers up to n and the sum of all even numbers up to m.
Then we will check for the bigger of the two m and n. Subtract the sum of smaller from the sum of bigger which will eventually give us the sum between m and n.
Formula
Sum of all even number from 0 to N is given by:
Example
const sumEven = n => (n*(n+2))/4;
const evenSumBetween = (a, b) => {
return a > b ? sumEven(a) - sumEven(b) + b : sumEven(b) - sumEven(a) + a;
};
console.log(evenSumBetween(-4, 10));
console.log(evenSumBetween(4, 16));
console.log(evenSumBetween(0, 10));
console.log(evenSumBetween(8, 8));
console.log(evenSumBetween(-4, 4));
24 70 30 8 0
How It Works
The algorithm uses a mathematical formula instead of iterating through each number:
// Step-by-step breakdown for evenSumBetween(-4, 10):
console.log("Sum from 0 to 10:", sumEven(10)); // 30
console.log("Sum from 0 to -4:", sumEven(-4)); // 6
console.log("Result:", 30 - 6 + (-4)); // 24
Sum from 0 to 10: 30 Sum from 0 to -4: 6 Result: 24
Alternative Iterative Approach
For better understanding, here's a simple loop-based solution:
function evenSumBetweenIterative(a, b) {
let min = Math.min(a, b);
let max = Math.max(a, b);
let sum = 0;
for (let i = min; i <= max; i++) {
if (i % 2 === 0) {
sum += i;
}
}
return sum;
}
console.log(evenSumBetweenIterative(-4, 10)); // 24
console.log(evenSumBetweenIterative(4, 16)); // 70
24 70
Conclusion
The mathematical approach using the formula N×(N+2)/4 provides O(1) time complexity, making it more efficient than iterating through each number. This solution works for both positive and negative ranges.
