Sum Of Odd Numbers

JavaScript Program To Find Sum Of Odd Numbers Less Than N

In our previous tutorials you learnt how to write a JavaScript program to find sum of N numbers and sum of N even numbers. In this tutorial, you’ll learn how to write a JavaScript program to find sum of odd numbers less than N.

Traditional Method To Find Sum Of Odd Numbers

Let’s first implement the solution to the above problem using traditional method. The program will iterate from 1 to N and check for number to be odd. If the number is odd, it’s added to the total sum.

Here is how the implement looks :

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

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

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

Mathematical Approach To Find Sum Of Odd Numbers

The traditional method to find the sum of N odd numbers can be optimized using the mathematical approach.

To find the sum of N odd numbers :

sum = 1 + 3 + 5 + 7 + … + (2n – 1) – EQ-1

From EQ-1 :

sum = (2-1) + (6-1) + (8-1) + … + (2n-1)

sum = (2+6+8+ …. + 2n) – n

sum = n*n + n -n

sum = n*n

Now let’s try to implement the above formula to calculate sum of odd numbers less than N.

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

/*
** Method to find sum of odd numbers less num
*/
function findSumOddNumbers(num) {
  let n = 0;
  if(odd(num)){
    n = (num - 1) / 2
  } else {
    n = num / 2
  }
  return n * n
}

console.log(`Sum is ${findSumOddNumbers(50)}`);

Wrapping It Up

In this tutorial, you learnt how to find the sum of odd numbers less than N using the traditional method and mathematical method. Do let us know your thoughts in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *