As a self taught developer I never did any of the Project Euler problems, so I decided to just start with Problem 1 which states
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.
The first step had been to create an extension method which takes a lowerLimit
and an upperLimit
returning an IEnumerable<int>
public static IEnumerable<int> GetSequence(this int lowerLimit, int upperLimit) { if (upperLimit < lowerLimit) { throw new ArgumentOutOfRangeException("lowerLimit needs to be less or equal to upperLimit"); } for (int i = lowerLimit; i < upperLimit; i++) { yield return i; } }
which can be called for instance like so
int lowerLimit = 1; var sequence = lowerLimit.GetSequence(1000);
I am not 100% sure about the name of that method but couldn't come up with an alternative name so for sure I would like to hear suggestions for that.
The meat about solving the problem
public static class SolverOfProblemOne { public static int Solve(this int lowerLimit, int upperLimit, params int[] multiples) { if (upperLimit < 0 || lowerLimit < 0) { throw new ArgumentOutOfRangeException("lowerLimit and upperLimit needs to be greater than or equal to 0"); } if (multiples == null || multiples.Length == 0) { return 0; } return lowerLimit.GetSequence(upperLimit) .Where(i => i.IsMultipleOf(multiples)) .Sum(); } private static bool IsMultipleOf(this int value, IEnumerable<int> multiples) { foreach (int multiple in multiples) { if (value % multiple == 0) { return true; } } return false; } }
To solve the actual problem one would call it like
int lowerLimit = 1; int upperLimit = 1000; int res = lowerLimit.Solve(upperLimit, 3, 5);
Any suggestions about the shown code are welcome. Because math has closed its doors for me after finishing school, I don't know if there is any math trick to do this any faster or easier.