PDA

View Full Version : C# multiples problem ...


rollcast
Dec8-11, 12:37 PM
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'm new to C# and I'm trying to solve this problem but there's no solution availible on Project Euler for it. I have made this bit of code and the result seems ok.

using System;

class MultipleSum
{
public static void Main()
{
int sum = 0;

for (int i = 0; i < 1000; i++)
{
if (i % 3 == 0)
sum += i;
continue;

if (i % 5 == 0)
sum += i;
continue;
}

Console.WriteLine(sum);
Console.WriteLine("Press ANY Key to continue");
Console.ReadKey();
}
}

Will that work for the problem?

Thanks
AL

I like Serena
Dec8-11, 01:33 PM
Hi rollcast! :smile:


I'm new to C# and I'm trying to solve this problem but there's no solution availible on Project Euler for it. I have made this bit of code and the result seems ok.

using System;

class MultipleSum
{
public static void Main()
{
int sum = 0;

for (int i = 0; i < 1000; i++)
{
if (i % 3 == 0)
sum += i;
continue;

if (i % 5 == 0)
sum += i;
continue;
}

Console.WriteLine(sum);
Console.WriteLine("Press ANY Key to continue");
Console.ReadKey();
}
}

Will that work for the problem?

Thanks
AL

What is your purpose for the use of "continue" in your program?

rollcast
Dec8-11, 01:44 PM
I thought I needed them to continue the loop after I performed the += operator?

I like Serena
Dec8-11, 01:50 PM
If you "continue" the loop, the rest of the loop is skipped and the next iteration starts.
Was that your intention?

Btw, the second "continue" is at the end of the loop and has as such no function.

AlephZero
Dec8-11, 01:52 PM
I thought I needed them to continue the loop after I performed the += operator?

Either you are using English in a fairly loose way, or you need to find out what the continue statement really does.

FWIW your code "works" because of the first continue statement, but the second one does nothing. But you wouldn't normally use a continue statement the way you used it.

http://www.cplusplus.com/doc/tutorial/control/

rollcast
Dec8-11, 02:06 PM
I was using the continue statements so in the event of a number, eg 60, that is both a multiple of 3 and 5 to stop it getting added twice? Or did I misinterpret the problem?

I like Serena
Dec8-11, 02:08 PM
You interpreted the problem correctly.
However, as it is now, you *always* continue, whether the number is a multiple of 3 or not.

rollcast
Dec8-11, 02:14 PM
using System;

class MultipleSum
{
public static void Main()
{
int sum = 0;

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

}

Console.WriteLine(sum.ToString());
Console.WriteLine("Press ANY Key to continue");
Console.ReadKey();
}
}


Is this code more correct then?

I like Serena
Dec8-11, 02:28 PM
Yep! :smile: