Home > front end >  for a given number N sum up all even numbers from 2 to N
for a given number N sum up all even numbers from 2 to N

Time:06-27

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.

CodePudding user response:

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));

CodePudding user response:

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

CodePudding user response:

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

  • Related