Question:
I need to make a function that takes a number X as a parameter and that returns the total of the sum of all the numbers that are even from 0 to X.
This makes 0+2+4+6+8+10+…..X.
But I don't know what else I need to add, because this is what I have so far and it doesn't return what I ask for:
function sumaDeLosParesDel0Al(x){
var suma = 0
for (var i=1; i<x; i++){
if (i%2 == 0) {
suma += i
}
}
return suma
}
console.log(sumaDeLosParesDel0Al(4));
Answer:
I propose you this algorithm that does not use loops.
There are exactly N/2
number of even numbers between 2
and N
, when N
is even, and (N-1)/2
even numbers when N
is odd.
The sum of the smallest ( N_0
) of these even numbers with the largest of them ( N_n
), is equal to the sum of the next largest even number ( N_1
) with the even number before the largest ( N_n-1
).
This is an arithmetic progression , which translates into the following formula:
const suma = n*(min + max)/2;
Where n
is the number of pairs between 0
and N
, in this case min
would be 2
and max
will be equal to N
when it is even and N-1
when it is odd.
So the algorithm can be as follows:
const sumaSoloPares = (numero) => {
if (numero < 2) return 0;
if (numero < 4) return 2;
const numOfPares = Math.floor(numero/2);
const min = 2;
const max = numero%2 === 0 ? numero : numero - 1;
const suma = ((min + max)*numOfPares)/2;
return suma;
}
console.log(sumaSoloPares(10));
console.log(sumaSoloPares(20));
console.log(sumaSoloPares(1345));
console.log(sumaSoloPares(15));
console.log(sumaSoloPares(40));
console.log(sumaSoloPares(41));
I hope this provides another insight into solving the problem.