- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Sum of even numbers from n to m regardless if n<m or n>m 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 −

$$\frac{N\times(N+2)}{4}$$

Therefore, let’s put all this into code −

## 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));

## Output

The output in the console will be −

24 70 30 8 0

- Related Questions & Answers
- Count of numbers satisfying m + sum(m) + sum(sum(m)) = N in C++
- Construct PDA for L = {0n1m2(n+m) | m,n >=1}
- Take two numbers m and n & return two numbers whose sum is n and product m in JavaScript
- Construct DPDA for anbmc(n+m) n,m≥1 in TOC
- Find a positive number M such that gcd(N^M,N&M) is maximum in Python
- Construct Pushdown automata for L = {0n1m2(n+m) | m,n = 0} in C++
- Construct DPDA for a(n+m)bmcn n,m≥1 in TOC
- Construct Pushdown automata for L = {0(n+m)1m2n | m, n = 0} in C++
- Construct Pushdown automata for L = {0m1(n+m)2n | m,n = 0} in C++
- Calculate n + nn + nnn + ? + n(m times) in Python
- Python Program to calculate n+nm+nmm.......+n(m times).
- How to check if two numbers (m,n) are amicable or not using Python?
- Construct Turing machine for L = {an bm a(n+m) - n,m≥1} in C++
- Calculate the value of (m)1/n in JavaScript
- Generating combinations from n arrays with m elements in JavaScript

Advertisements