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

前端 未结 7 1700
失恋的感觉
失恋的感觉 2020-12-22 05:27

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

相关标签:
7条回答
  • 2020-12-22 06:19

    What you are doing is some calculation error. You see there are some common multiples of 5 and 3 like 15,30,45... so since you are adding these in both the sums you are getting a higher value.

    A slight modification to the code will do the trick.

    for(x= 0; x < 1000; x += 3) 
    {
       if(x%5)
       {
           a = a + x;
       }
    }
    
    for(y = 0; y < 1000; y += 5)  
         b = b + y;
    
    z = a + b;
    printf("%lu", z);
    
    0 讨论(0)
提交回复
热议问题