Sum of all the multiples of 3 or 5 below 1000 gives a wrong answer in C

  • A+
Category:Languages

Project Euler problem:

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.

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

My C code:

long int x;  long int y;  long int z = 0;  long int a = 0;  long int b = 0;  for(x= 0; x < 1000; x += 3)       a = a + x;  for(y = 0; y < 1000; y += 5)       b = b + y;  z = a + b; printf("%lu", z);  return 0; 

But I'm getting 266333 as the output which is wrong. I checked the answer with Python and I got it right. I would like to know what I'm doing wrong with the C code. The right answer is 233168

My Python code:

print(sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0)) 

 


Some numbers will be divisible by both 3 and 5, you should not add them twice. A code like this will give correct result:

long int x,total = 0;  for(x = 0; x < 1000; ++x) {     if(x % 3 == 0)         total = total + x;     else if(x % 5 == 0)         total = total + x; }  printf("%ld", total); 

in the code above if else if make sure that if a number is divisible by 3 or by 5. And allow to sum up on this basis.

It can further be optimized to:

for(x= 0; x < 1000; ++x) {     if(x%3 == 0 || x%5 == 0)         total = total + x; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: