Ripsaw
Ripsaw

Reputation: 27

ProjectEuler Q1 Program unexpected result

I was working on problem one and my original program looked like this

int multiplesof=1000,count=0, multiple1 = 3, multiple2 = 5,val1,val2,sum=0;

while (count < multiplesof)
{
    if (count % multiple1 == 0)
        sum = sum += count;
    if (count % multiple2 == 0)
        sum = sum += count;
    count++;
}
Console.Out.WriteLine(sum + " is the sum of all multiples");
Console.In.ReadLine();

It give me the solution of 266333. This proved to be wrong, stumped I looked at Google. I have since gotten the correct value of 233168 with the following loop. However to me they look like they do exactly the same thing. Could anyone please explain why they are bring up different answers?

while (count < multiplesof)
{
    if (count % multiple1 == 0 || count % multiple2 == 0)
        sum = sum += count;
    count++;               
}

Upvotes: 0

Views: 59

Answers (2)

neeKo
neeKo

Reputation: 4280

Because you added twice if it was a multiple of both 3 and 5, like when it was 15.

An alternative solution and also a spoiler if you were going to try to solve it yourself:

int result = 3 * (999 / 3 * (999 / 3 + 1) / 2) + 5 * (999 / 5 * (999 / 5 + 1) / 2) - 15 * (999 / 15 * (999 / 15 + 1) / 2);

Upvotes: 5

Joni
Joni

Reputation: 111299

Think about numbers that are divisible by both 3 and 5, such as 15. Your first attempt counts them twice.

Upvotes: 0

Related Questions