Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

119
Visualizações
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 !

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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;

}
about 4 years ago · Juan Pablo Isaza Relatório

0

I'd suggest using Array.reduce() to get the desired result. We generate all integers from 1 to N using Array.from(), then use .reduce() to add any odd numbers to the sum (accumulator) value.

function getSumOfOddNumbers(n) {
    return Array.from({length: n}, (v,k) => k + 1).reduce((sum, cur) => (cur % 2) ? sum + cur: sum, 0);
}

for(let n = 1; n < 10; n += 2) {  
    console.log(`Odd number sum from 1 to ${n}:`, getSumOfOddNumbers(n));
   }
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda