[Solved] Using Java: Find the sum of all the multiples of 3 or 5 below 1000. (What’s wrong with my algorithm?) [duplicate]


You are counting numbers like 15, 30… (which are multiple of both 3 and 5) two times. So one alternative is to subtract these counts, you can add following loop after your two loops:

for (int i = 0; i < 1000; i+=15) {
    count-=i;
}

You can also do the same in one loop (More efficient):

for (int i = 0; i < 1000; i++) {
    if(i%15 == 0) count+=i;   
    else if(i%3 == 0 || i%5 == 0) count += i;
} 

solved Using Java: Find the sum of all the multiples of 3 or 5 below 1000. (What’s wrong with my algorithm?) [duplicate]