Search code examples
javascriptfiltersum

Sum odds in integer N - JavaScript


I'm trying to make a function that will calculate the sum of the odds in a N integer.

For example, if N = 5 => 1+3+5 = 9

Here is my attempt :

const n = 4

let arr = []
let i = 0
while (i < n) {
    i++
    arr.push(i)
}

console.log(arr)

This code return an array with all integers in N, that's ok.

Now I would like to filter the odds, then make the sum of it. I tried different things without success.

Thank you for your time !


Solution

  • const calculateSum = (n) => {
      
      let sum = 0;
    
      // Start from 1 and increment by 2 (1, 3, 5, 7, 9, 11, etc)
      for(let i = 1; i <= n; i+=2) {
        sum += i;
      }
      return sum;
    
    }