Project Euler’s first problem

Hi everyone!

This if my first post on my Project Euler series. As I mentioned in my previous blog post, Project Euler is a series of mathematical challenges that are meant to be solved using computer programming. Given my interests in both of those fields, it only seemed natural that I would start writing about this… so here we are!

The first problem is called “Multiples of 3 or 5,” and it is fairly simple. I have transcribed the full problem below:

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 know my readers familiar with Robert Anton Wilson won’t be surprised to find the number 23 popping up here…

Anyway, I actually have a bit of experience in programming, so I didn’t exactly need to watch any in-depth tutorials on programming before jumping into it. I decided to use Python with the PyCharm IDE, given how simple these are. Given my familiarity with programming functions, all I really needed to lookup was the syntax of the language. In any case, my code can be found below:

mul = []
max = 1000
sum = 0

for i in range (1, max):
    if i%3 == 0 or i%5 == 0:
        mul.append(i)

for j in range (0, len(mul)):
    sum = sum + mul[j]

print("The sum of the natural numbers below", max, "that are multiples of 3 or 5 is equal to:", sum)

Naturally, we have a simple “for loop” to create an array that contains all the multiples of 3 and 5 that are smaller than our maximum number, and a second “for loop” that will add all of these numbers up. I initially set max equal to 10 to test my code, and I did indeed get 23, see below:

Once I knew that my code was functional, all I had to do was change the max value to 1000 to get the following result:

An earlier version of the code included a line that actually printed all the multiples of 3 and 5, but the array got quite long. I tried breaking it down into smaller arrays so that the length of each array would be approximately the same length as the other printed lines, but it got pretty complicated pretty quickly (for loops within for loops are tricky!) and, after realizing that this was outside the scope of the assignment, I happily removed all superfluous lines and went back to writing this blog post…

See you next time!

Jo

Leave a comment