Project Euler - Multiples of 3 and 5

Fizz Buzz


When I was at school this game was known as Fizz Buzz.  We'd sit in a circle and starting at 1, each person in the circle would say the next number. "One", "two" etc When it's a player's turn to say a number divisible by 3, they say, "fizz" and a number divisible by 5, they say, "buzz".  So, when you get to 15, the player says, "fizz buzz".  As a Maths nerd, this was one of my favourite games at school!  

The first Project Euler challenge is a lot like Fizz Buzz.  To quote the website, it looks like this:

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.

There may be a quicker way of coding this than my method, but I like to keep things neat and this seemed like a great way to make use of C#'s IEnumerable collection.

        public static IEnumerable<long> EnumerateMultiples(long Factor, long                     maxMultiple)

        {

            long current = 1;

            long multiple = 0;

            long sum = 0;

            do

            {

                multiple = current * Factor;

                yield return multiple;

                sum = sum + multiple;

                current++;

            } while (multiple < (maxMultiple - Factor));

        }

Then in the Main() method:

            const long firstFactor = 3;

            const long secondFactor = 5;

            // multiples of 15 will be counted twice so we need to remove one set

            const long eliminateFactor = 15;

          const long maxValue = 1000;

            // Declare an interface to the iEnumerable 

            IEnumerable<long> firstSequence = EnumerateMultiples(firstFactor, maxValue);

            IEnumerable<long> secondSequence = EnumerateMultiples(secondFactor, maxValue);

            IEnumerable<long> eliminateSequence = EnumerateMultiples(eliminateFactor, maxValue);

            // Get the sum of each list of multiples

            long firstTotal = firstSequence.Sum();

            long secondTotal = secondSequence.Sum();

            long eliminateTotal = eliminateSequence.Sum();

            // (sum of 3s) + (sum of 5s) - (sum of 15s) - put over-simply

            long totalMultiples = firstTotal + secondTotal - eliminateTotal;

            Console.WriteLine(firstTotal + " + " + secondTotal + " - " + eliminateTotal + " = " + totalMultiples);

The whole of my code can be found on my GitHub.

Picture attribution:  Velroy Fernandes from Pexels

Comments