Wednesday 3 February 2016

Project Euler #1: Multiples of 3 and 5

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.

I'm feeling lazy so I'll do a quick post about the first problem since it's pretty straightforward. All I did was  loop through every number from 1 until the limit and test if either 3 or 5 was a divisor. Brute force ftw! Including the printing this takes 0.002 seconds.

Even still, I can think of a few things to speed it up if only trivially.
  1. Use something other than mod
  2. Instead of incrementing by 1, keep two counters - one for 3 and the other for 5. Increment whichever one is lower and add it to the sum until both counters reach the limit. This way you save on having to test if the number is a multiple of 3 or 5. You do however need to check if your two counters are equal. If they are then you skip that number.
The second solution might deserve to be coded for clarity if there's any interest. Be sure to check out the solution thread as there are some nice ways to get the answer without any coding.

Edit: The code is not formatted properly when embedded here for whatever reason

No comments:

Post a Comment