Mathijs - 5 months ago 35

C# Question

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.

I tried to make the first problem from projecteuler.net. My code is as follows:

`int check = 3;`

int result = 0;

for (int i = 1; i < 1000; i++)

{

if (i == check)

{

result += i;

check += 3;

}

}

check = 5;

for (int i = 1; i < 1000; i++)

{

if (i == check)

{

result += i;

check += 5;

}

}

Console.WriteLine(result);

Console.ReadKey();

I know it can be optimalised way better, but my code doesn't work and i don't know why. I tested it with 10 instead of 1000 and then it works. Does anybody see the mistake?

Edit: My code does work, but I get the wrong result. I get the right result when i use i < 10 in the for loop

Answer

The problem with your code is:

You're checking numbers from 1 to 1000 once, which are multiple of 3. And, next you're also checking the numbers from 1 to 1000 next, which are multiple of 5.

But, you forgot the case that there can be several numbers which are multiples of both 3 and 5(e.g.,15,30,etc).

So, you should perform your operation in a single loop instead of checking it first by 3 and next by 5.

Do like :

```
int sum = 0;
for(int i=lower_limit;i<=upper_limit;i++){
if(i%3==0 || i%5==0)
sum = sum+i;
}
```