computeSum

Compute the sum of all integers that are multiples of 5, from 1 to 100

1 Like

i tried this(see below) but it is failing, saying Must be a number greater than 0:

function computeSum(integers) {
    var sum = 0;

    for (var x = 5; x < integers.length; x += 5) {
        if (x % 5 === 0 && x > 0) {
            sum += x;
            //console.log(x);
            //console.log(sum);
        }
    }

    return sum;
}
computeSum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]);

why do you have the array? You could simply use a loop to get all numbers you need from the loop.

nowhere in your code i see such a message

Thanks for your response and correction, I changed it to this:
function computeSum(integers){
var sum = 0;
var integerNum = [];
for(var i=1; i < 101; i++){
integerNum.push(i);
console.log(integerNum);
}
integers = integerNum;

for (var x = 5; x < integers.length; x += 5) {
    sum += x;
    console.log(x);
    console.log(sum);
}

return sum;

}
computeSum([integers]);

but still return error that => Must be a number greater than 0

is this an exercise? If so, please share exercise url

now you have two loops, why? We can get the values we need from a loop, and add them to sum. So we only have a single loop, that is all that is needed, unless assignment requirements say otherwise

you dont need an array , keep it simple

please remember the requirement to Compute the sum of all integers that are multiples of 5, from 1 to 100. regards.

We can just use a for loop to get all the values you need, then inside the for loop you can add these values directly to sum

is this a codecademy exercise, if so, please share exercise url

what assignment is this?

so you have a isMultipleOfFive helper function which you must use?

This should work for you and I believe it provides a solution to everything in your assignment:

const integers = [];
for (let i = 1; i <= 100; i++) integers.push(i); // populate with integers from 1 to 100

const isMultipleOfFive = (int) => int % 5 === 0; // return true if int is multiple of 5

const computeSum = (ints) => { // given ints, computes required sum
    let sum = 0;
    for (let i = 0; i < ints.length; i++) if (isMultipleOfFive(ints[i]) && ints[i] > 0) sum += ints[i];
    return sum;
};

let sum = computeSum(integers); // invoke with integers from 1 to 100
console.log(sum); // 1050

Edit: woops, just realised I’m a couple years too late…