How to add the elements of Array?

2

Hi, I am trying to create a program that adds the multiples of 3 and 5 that are between 0 and 10. Well, I do not know what I'm doing wrong that the sum gives me 33, when it should be 23. Do you see the error in my code ...? Thanks.

function multiple(valor, multiple) {
    resto = valor % multiple;
    if (resto == 0)
        return true;
    else
        return false;
}

// Arrays que contendran los valores multiples del 3 y del 5
let multiples_3 = [];
for (let i = 1; i <= 10; i++) {
    if (multiple(i, 3))
        multiples_3.push(i);

    if (multiple(i, 5))
        multiples_3.push(i);
}

let a = multiples_3
let suma = 0;
for (let i = 0; i < multiples_3.length; i++) {
    suma += multiples_3[i]
}
alert(suma)
    
asked by Miguel Espeso 14.05.2018 в 00:43
source

1 answer

3

If limit 10 is open (ie you should not consider 10) the problem is using operator <= instead of < in the for

for (let i = 1; i < 10; i++) {

The corrected code (with certain redundancies removed) would be

function multiple(valor, multiple) {
    return valor % multiple === 0;
}

// Arrays que contendran los valores multiples del 3 y del 5
let multiples_3 = [];
for (let i = 1; i < 10; i++) {
    if (multiple(i, 3))
        multiples_3.push(i);

    if (multiple(i, 5))
        multiples_3.push(i);
}

let suma = 0;
for (let i = 0; i < multiples_3.length; i++) {
    suma += multiples_3[i]
}

alert(suma);
    
answered by 14.05.2018 / 03:12
source