Skip to content Skip to sidebar Skip to footer

Find Sum Of Iterations Of Variable In For Loop

for (i = 0; i <= 1000; i++) { if ( i % 3 === 0){ console.log(i); } if ( i % 5 === 0){ console.log(i); } } I want to add each output of i togeth

Solution 1:

The sum of the numbers from 1 up to n is

n * (n + 1) / 2

The sum of the numbers from 1 up to 1000 that are divisible by 3 is the same as the sum of the numbers from one up to 1000 / 3, multiplied by 3. Similarly, the sum of the numbers from 1 to 1000 that are divisible by 5 is the same as the numbers from 1 to 1000 / 5, multiplied by 5.

I bet the problem you're working on wants you to exclude numbers that are divisible by 15 :)

edit — Why does this work? Well, consider the simpler case of the numbers from 1 to n; say, 1 to 100.

1, 2, 3, 4, 5, ... 97, 98, 99, 100

Now, consider that same list of numbers, but backwards:

100, 99, 98, 97, ... 4, 3, 2, 1

Note than when we add pairs from those two lists, we always get 101:

100 + 1is10199 + 2is10198 + 3is101
...
4 + 97is1013 + 98is1012 + 99is1011 + 100is101

So there are 100 sums all the same, that being 101. If we do that multiplication and divide by 2, we've got the answer :)

Now, what about the sum of the numbers divisible by 3, or 5? Well if you think about it, what do those numbers look like?

3, 6, 9, 12, ... 993, 996, 999

Hmm... that looks a lot like

3 * (1, 2, 3, 4, ... 331, 332, 333)

So the sum of the numbers 1 through 333 is 333 * 334 / 2, and if we multiply that by 3 we get the sum of the numbers from 1 to 1000 that are divisible by 3. Same goes for 5. If we want to drop the sum of the numbers divisible by both 3 and 5, we'd compute the sum of the numbers from 1 to 1000 / 15 and subtract that from the result.

Oh, and one more thing. If we're talking about a sum of integers, how do we know that that step where we divide by 2 won't leave us with a fraction? Well, the formula is n * (n + 1) / 2, remember. If n is an odd number, then n + 1 is even. Thus, that multiplication will always involve one even number, so dividing by 2 will never leave us with a fraction!

Solution 2:

Just create a variable outside the loop to keep a running total:

intsum = 0;
for (i = 0; i <= 1000; i++) {
    if ( i % 3 === 0){
        sum += i; // orsum = sum + i
    }
    if ( i % 5 === 0){
        sum += i; // orsum = sum + i
    }
}

console.log(sum);

Solution 3:

If you want to avoid counting multiple of 15 twice in your sum :

intsum = 0;
for (i = 0; i <= 1000; i++) {
    if ( i % 3 === 0 ||  i % 5 === 0){
        sum += i; // orsum = sum + i
    }
}

Post a Comment for "Find Sum Of Iterations Of Variable In For Loop"