Do you need “Project Euler Problem 5 Solution Python”? We will discuss all the problems in Project Euler and try to solve them using Python. I have solved Project Euler Problem 4 Python as well.
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
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. Or you can make this work on any online python editor as well. Such as Repl.it.
If we analyze the problem statement given here, we can see that we are asked to find the smallest number that completely divides all of the numbers from 1 to 20.
Project Euler Problem 5 Solution in Python
The first thing that comes to my mind is brute force. I think that it is the only and simplest way to find that if a number divides every number from 1-20 or not by checking for each of them.
We make a function that returns true if the number is divisible by all numbers from 1-20 (2,20 technically because every number is divisible by 1 so there is no point of checking it for 1 😉 )
def ifDividesAll(num): for i in range(2,21): if num % i != 0: return False return True
Now we do a loop that keeps on incrementing the number and check for each using the function ifDividesAll. If the function returns true the loop breaks and we print the number otherwise, it keeps on adding one to the number, check again and again and again…
num = 20 while True: if ifDividesAll(num): break else: num = num + 1 print num
Let us see if we got it right.
Yaay! We got this right. Thanks for reading.