Q:

Optimising Javascript

I was given a quiz and I had gotten the answer wrong and It's been bugging me ever since so I thought I'd ask for your thoughts
I needed to optimise the following function
function sumOfEvenNumbers(n) {
    var sum = 0;
    for(let i = 2; i < n;i++){
      if(i % 2 == 0) sum += i;
    }
    return sum;
 }

 console.log(sumOfEvenNumbers(5));

I came up with 
function sumOfEvenNumbers(n) {
    var sum = 0;
    while(--n >= 2) sum += n % 2 == 0? n : 0
    return sum;
}

console.log(sumOfEvenNumbers(5));

What other ways were there?

A:

Sum of n numbers:
var sum = (n * (n+1)) / 2;

Sum of n even numbers:
var m = Math.floor(n/2);
var sum = 2 * (m * (m+1) /2);

A:

It's a bit of a math question. The sum appears to be the sum of an arithmitic sequence with a common difference of 2. The sum is:
sum = N * (last + first) / 2;

where N is the number of the numbers in the sequence, last is the last number of those numbers, and first is the first.
Translated to javascript as:
function sumOfEvenNumbers(n) {
    return Math.floor(n / 2) * (n - n % 2 + 2) / 2;
}

Because the number of even numbers between 2 and n is Math.floor(n / 2) and the last even number is n - n % 2 (7 would be 7 - 7 % 2 === 6 and 8 would be 8 - 8 % 2 === 8). and the first is 2.

