# Thread: For one set of values answer is valid & for another set of values,answer invalid

1. ## For one set of values answer is valid & for another set of values,answer invalid

/*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. */

Code:
```#include<stdio.h>
int main()
{
int i=1,m3=0,n;
for(;i<10;i++)
{
if(((n=i*3)<10))
m3+=n;
if((n=i*5)<10)
m3+=n;
}
printf("res=%d\n",m3);
return 0;
}
```
When I put 10 the answer is 23,when I try for 1000,output:266333,which is a wrong answer according to the eulerproject.net
What is wrong in the program? 2. I'd imagine that it's because you're summing a lot of numbers twice. E.g. 15 is a multiple of 3 and of 5, and your code will add it twice. Since there aren't any common multiples of 3 and 5 below 10, you wouldn't see the problem there. 3. Hi Shruthi,

Your code is adding numbers which are multiples of both 3 and 5 twice.
That's why you got wrong answer.

Try this
Code:
```if(((n=i*3)<10)) {
m3+=n;
}
else {
if((n=i*5)<10)
m3+=n;
}
``` 4. Or to write less code
Code:
```if( ( (n=i*3)<10 ) || ((n=i*5)<10)
m3+=n;``` 5. I've used the above suggestion and still haven't got the right solution.It's not even satisfying the first condition,23.it's giving 18 because it not considering 5*1=5,it's only considered 3*1=3 and given the result 18. 6. Your idea in the code you posted in post #1 looks like it should work, but your code is rather messy. Here's an improved version:
Code:
```#include<stdio.h>

int main(void)
{
int sum = 0;
int i;
for (i = 1; i < 1000; i++)
{
if (i % 3 == 0)
{
sum += i;
}
if (i % 5 == 0)
{
sum += i;
}
}
printf("sum=%d\n", sum);
return 0;
}```
Notice that I got rid of the n variable, because you should not have been adding n to the sum (i.e., I fixed another bug for you, for free). However, I have left your double counting problem in the code for you to fix. It really is very easy to fix it now Hint: notice that for both the if statement, the body is exactly the same. Can you combine them into a single if statement? 7. Thank you laserlight,finally got the answer. Code:
```#include<stdio.h>
int main()
{
int i,sum=0;
for(i=1;i<1000;i++)
{
if((i%3==0) && (i%5==0))
sum+=i;
else
{
if(i%3==0)
sum+=i;
if(i%5==0)
sum+=i;
}
}
printf("sum=%d\n",sum);
return 0;
}
``` 8. That's good, though what I had in mind was:
Code:
```#include<stdio.h>

int main(void)
{
int sum = 0;
int i;
for (i = 1; i < 1000; i++)
{
if (i % 3 == 0 || i % 5 == 0)
{
sum += i;
}
}
printf("sum=%d\n", sum);
return 0;
}``` 9. and also you can club this in a single statement
Code:
```if((i*3==0) || (i*5==0)
sum+=i;``` 10. Ok,got ur point  Popular pages Recent additions 