Find the sum of all the multiples of 3 or 5 below 1000

前端 未结 16 947
时光说笑
时光说笑 2020-12-10 16:41

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. I have the following code but the answer do

16条回答
  •  一整个雨季
    2020-12-10 17:07

    You might start by iterating from 3 to 1000 in steps of 3 (3,6,9,12,etc), adding them to the sum like,

    int i = 3, sum = 0;
    for (; i < 1000; i += 3) {
      sum += i;
    }
    

    Then you could iterate from 5 to 1000 by 5 (skipping multiples of 3 since they've already been added) adding those values to the sum as well

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

    Then display the sum

    printf("%d\n", sum);
    

提交回复
热议问题