this gives the amount 200003
#include <stdio.h>
int main(void){
int i = 0;
int x = 0, x15 = 0;
for (i=0; i<1000; i++){
if (i%3==0 || i%5==0){
x += i;
}
if (i%15==0){
x15 += i;
}
}
printf("%d'\n", x-x15);
return 0;
}
this gives the amount 233168
#include <stdio.h>
int main(void){
int i = 0;
int x3 = 0, x5 = 0, x15 = 0;
for (i=0; i<1000; i++){
if (i%3==0){
x3 += i;
}
if(i%5==0){
x5 += i;
}
if (i%15==0){
x15 += i;
}
}
printf("%d\n", x3+x5-x15);
return 0;
}
can anyone explain what’s different between the two? I would expect the two to provide the same output.
Multiple of 15 will be added to both x3 and x5 in the bottom code, so they are counted twice. In the top version, each is counted only once.