Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
for a given number N sum up all even numbers from 2 to N

I was taking a test and the and the question was : make a function for a given number N sum up all even numbers from 2 to N.

i make this function but i want to know how i can make it better like if i enter a odd number.

for the example they give me:

the input was : 10 and the output was 30.

my function:

function sumUp(N) {
  var sum = 0
  var sumTemp = 0
  const start = N
    for(let i = 1; i < N ; i++) {
        if(N === 2) {
        sum = 2
      } else {
        if(i%2 === 0) {
          sumTemp = sumTemp + i
        }
      }
      sum = start + sumTemp
    }
  return console.log(sum)
}

sumUp(10);

thanks in advance.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Yes, you can make it better.

function sumUp(N) {
  var sum = 0
  for (var i = 2; i < N; i += 2) {
    sum += i
  }
  return sum
}

console.log(sumUp(7));

about 4 years ago · Juan Pablo Isaza Denunciar

0

you can do it using this simple function:

function solve(N) {
  N = N - N % 2;
  let odd = N / 2;
  let even = N * (N + 1) / 2 - odd * odd;
  return Math.floor(even);
 }

It works in O(1) time

about 4 years ago · Juan Pablo Isaza Denunciar

0

A better function would be something like the following:

function sumUp(N) {
  let sum = 0
  for(let i = 2; i <= N ; i+=2) {
    sum += i
  }
  return console.log(sum)
}

It works, seen here:

https://imgur.com/PIJax7Q.png

https://imgur.com/PIJax7Q.png

https://imgur.com/gWiV1Hb.png

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda