Project Euler problem 1

Source code available on GitHub.

This first problem gets us off to an easy start. It asks:

  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.

We want to iterate through all the numbers below 1000, so we’ll use a for loop:

for i in range(1,1000):

This tells Python to start with i=1 and keep incrementing i every loop up until i=999. The easiest way to check for divisibility is with the modulus operator, %. Writing x % y returns the value of x \mod y – that is, the remainder when dividing x by y.

So, using an if statement, we write

if i % 3 == 0 or i % 5 == 0:

which will return true when the number is a multiple of (had zero remainder when divided by) either 3 or 5. If this happens, we want to add i to some sum so that when the for loop terminates, that value is our final value. We’ll call it running_sum.

Lastly, we want to print the result. Here’s the final code:

running_sum = 0
for i in range(1,1000):
    if i % 3 == 0 or i % 5 == 0:
        running_sum += i
print(running_sum)

Leave a Reply

Your email address will not be published. Required fields are marked *