- Related Questions & Answers
- Take two numbers m and n & return two numbers whose sum is n and product m in JavaScript
- 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 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).
- Construct Turing machine for L = {an bm a(n+m) - n,m≥1} in C++
- How to check if two numbers (m,n) are amicable or not using Python?
- Generating combinations from n arrays with m elements in JavaScript
- Print first m multiples of n in C#
- Cost of painting n * m grid in C++
- Construct Pushdown automata for L = {a(2*m)c(4*n)dnbm | m,n = 0} in C++
- Implementing Math function and return m^n in JavaScript
- Calculate n + nn + nnn + … + n(m times) in Python program

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

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

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.

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 −

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

The output in the console will be −

24 70 30 8 0

Advertisements