Find sum of iterations of variable in for loop

前端 未结 3 1180
谎友^
谎友^ 2021-01-17 00:31
for (i = 0; i <= 1000; i++) {
    if ( i % 3 === 0){
        console.log(i);
    }
    if ( i % 5 === 0){
        console.log(i);
    }

}

I wan

相关标签:
3条回答
  • 2021-01-17 01:11

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

    int sum = 0;
    for (i = 0; i <= 1000; i++) {
        if ( i % 3 === 0){
            sum += i; // or sum = sum + i
        }
        if ( i % 5 === 0){
            sum += i; // or sum = sum + i
        }
    }
    
    console.log(sum);
    
    0 讨论(0)
  • 2021-01-17 01:13

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

    int sum = 0;
    for (i = 0; i <= 1000; i++) {
        if ( i % 3 === 0 ||  i % 5 === 0){
            sum += i; // or sum = sum + i
        }
    }
    
    0 讨论(0)
  • 2021-01-17 01:20

    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 + 1 is 101
    99 + 2 is 101
    98 + 3 is 101
    ...
    4 + 97 is 101
    3 + 98 is 101
    2 + 99 is 101
    1 + 100 is 101
    

    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!

    0 讨论(0)
提交回复
热议问题