Multiples of 3 and 5
How to solve “Multiples of 3 and 5” from Project euler. We will discuss all the problems in Project Euler and try to solve them using Python.
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.
So we have to solve this problem using Python.
I am assuming you have already installed Python 2.7.x. If not, you can download it from here.
Lets first of all open Python IDLE.
If we analyze the problem statement given here, we can see that we are asked to calculate the sum of those natural numbers who complies to the following conditions.
Let’s say we call our natural number to be summed as x
- x is below 1000
- x is multiple of 3
- OR x is multiple of 5
We have to sum these “x” numbers.
We need to save the sum of such x numbers into some variable.
sum = 0
Now let’s make a list to store all the natural numbers below 1000.
nums = range(1,1000)
We have to iterate the items of this list and see if the number is a multiple of 3 or 5. If it is we will add that number to the sum variable otherwise we will just skip.
for i in nums: for i in nums: if i % 3 == 0 or i % 5 == 0: sum = sum + i
Now lets display the sum. It show that 233168 is the number of such elements.
Lets see if we got it right.
Yaay! We got this right. Thanks for reading. Happy coding!
Project Euler Problem 2 Even Fibonacci Numbers solution here.