Project Euler - Multiples of 3 and 5
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
Post a Comment