views:

181

answers:

3

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 does not match.

#include<stdio.h>
int main()
{
    long unsigned int i,sum=0;
    clrscr();
    for(i=0;i<=1000;i++)
    {
        if((i%5==0)||(i%3==0))
        {
            sum=sum+1;
        }
    }
    printf("%d\n",sum);
    getchar();
    return 0;
}
+5  A: 

Perhaps you should do

sum += i // or sum = sum + i

instead of

sum = sum + 1

Additionally, be careful when printing long unsigned ints with printf. I guess the right specifier is %lu.

Hugo Peixoto
was forgetting %lu thanks
fahad
+4  A: 

It should be sum = sum + i instead of 1.

Eric Fortin
+6  A: 

Two things:

  • you're including 1000 in the loop, and
  • you're adding one to the sum each time, rather than the value itself.

Change the loop to

for(i=0;i<1000;i++)

And the sum line to

sum=sum+i;
martin clayton
Its printing some garbage.I even changed int to long int
fahad
I get 233168 once those changes are in place, and a warning about the format (see Hugo's Answer). Is that the right value?
martin clayton
@martin: yes, that's the right answer (according to Project Euler).
Steve Jessop