Spoiler Alert: As the About page of Project Euler says, "Real learning is an active process and seeing how it is done is a long way from experiencing that epiphany of discovery." If you are currently attempting to solve this problem in the archives, please do not continue to read this post. I personally worked through all the problems I post on this blog and it has brought me immense satisfaction.
Problem: 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:
This problem can be solved brute-force without too much difficulty by simply doing a for loop from 1 to 999, incrementing by one each time, checking each number to see if it is divisible by either 3 or 5, and if so, adding it to a list. Once the for loop terminates, we can sum all the numbers in the list.
In C#, you do something like this:
Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); List<int> multiples = new List<int>(); for (int i = 1; i < 1000; i++) { if (i % 3 == 0 || i % 5 == 0) { multiples.Add(i); } } stopwatch.Stop(); Console.WriteLine($"Elapsed time (ms): {stopwatch.Elapsed.Milliseconds}"); Console.WriteLine($"Count: {multiples.Count}"); Console.WriteLine($"Sum: {multiples.Sum()}"); Console.ReadLine();
I don't know how many nanoseconds it took, but it took less than 1 millisecond on my machine.
Using LINQ instead of the for loop and leaving everything else the same:
var multiples = Enumerable.Range(3,999-2).Where(x => x % 3 == 0 || x % 5 == 0);
This took 3 milliseconds! I also find it much less readable.
We can figure out how many integers are divisible by 3 or 5 using mental math or a calculator. Recognize that 5 divides 1000 200 times, so it divides 999 199 times, and 3 divides 999 333 times. Therefore we have a total of 532 minus the duplicates of any multiples of 15. If you can't divide 1000 by 15 easily (I couldn't), the answer is 66. So there are 199 + 333 - 66 = 466 different multiples of either 3 or 5 in the range 1:999.
I've avoided putting the answer in the solution, just in case someone solving the problem on Project Euler ignored the Spoiler Alert. But either of these methods will provide the correct answer.
Comments
Post a Comment