Project Euler 001 – C#

1 02 2011

Problem 1

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.

Solution

namespace ProjectEulerCSharp_001

{

    //Add all the natural numbers below one

    //thousand that are multiples of 3 or 5.

 

    //first, we will get all of

    //the numbers divisible by 3

    class Program

    {

        static void Main(string[] args)

        {

            int answer = 0;

 

            // add the 3’s, the 5’s, and subtract one set of 15’s

            for (int three = 0; three < 1000; three += 3)

              { answer += three; }

            for (int five = 0; five < 1000; five += 5)

              { answer += five; }

            for (int fifteen = 0; fifteen < 1000; fifteen += 15)

              { answer -= fifteen; }

 

            System.Console.WriteLine(answer);

        }

    }

}

 

Discussion

If you saw the F# solution then this should be a relatively easy translation.  The main difference is that I create the sum as I’m building the list.

If you have questions, leave a comment or find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).


Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s




%d bloggers like this: