find sum of even numbers

How To Find Sum Of Even Numbers Less Than N

In this tutorial, you’ll learn how to write a JavaScript program to find sum of even numbers less than N. We’ll be following two approaches to accomplish this task. One would be the traditional method using looping and other would be a mathematical approach.

Traditional Approach To Find Sum Of Even Numbers Less Than N

The traditional approach will be to check if a number is even and then sum it along with other even numbers. Let see how you can implement the same.

/*
** Method to check if a number is even
*/
function even(n){
  return !Boolean(n%2)
}

/*
** Method to find sum of even numbers less than n
*/
function findSum(n) {
  let sum = 0;
  for(let i = 0; i <= n; i++){
    if(even(i)) {
      sum += i;
    }
  }
  return sum
}

console.log(`sum is ${findSum(100)}`)

As seen in the above code, you iterated from 1 to N. Check if the number is even and sum it along with other even numbers. Now as you can see the logic involves iterating a loop from 1 to N and checking each number against even method.

Mathematical Approach To Find Sum Of Even Numbers

Let’s have a look at how a mathematical approach to the above problem gives a more optimized solution. To find the sum of N numbers :

1 + 2 + 3 + 4 + 5 + 6 + ………….. + N

Assume the sum to above equation to be sum

sum = 1 + 2 + 3 + 4 + 5 + 6 + ………….. + N  —  EQ-1

Reverse the above series and add the numbers backwards which will also give the same sum.

sum = n + (n-1) + (n-2) + (n-3) + (n-4) + ……. + 1  — EQ-2

Adding EQ-1 and EQ-2, you get

2(sum) = (n+1) + (n+1) + (n+1) + (n+1) + ……. (n+1)

2(sum) = n times (n+1)

sum = (n times (n+1)) / 2 — EQ-3

The problem at hand is to find sum of N even numbers,

2 + 4 + 6 + 8 + 10 + …… + 2N

The above sum if equivalent to

2 times (1 + 2 + 3 + 4 + 5 + …… + N) — EQ-4

Based on EQ-3 and EQ-4, you can derive that

sum of N Even numbers = n*n + n

Let’s try to implement the same using JavaScript.

/*
** Method to find sum of even numbers less than N
*/
function findSumEvenNumbers(num) {
  let n = 0;
  if(even(num)){
    n = num/2
  } else {
    n = (num - 1)/2
  }
  return n*n + n
}

console.log(`Sum is ${findSumEvenNumbers(100)}`);

Wrapping It Up

In this tutorial, you learnt how to find the sum of even numbers less than N using JavaScript. Do you know of any other method of finding the sum of even numbers ? Do let us know your thoughts in the comments below.