Python Forum
My code is taking longer time to give result - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: My code is taking longer time to give result (/thread-16270.html)



My code is taking longer time to give result - rajeshwin - Feb-20-2019

I am newbie to Python and tried to write a code to get smallest positive number that is evenly divisible by all of the numbers from 1 to 20. I used the script provided below. It is taking more time to get the result.
How can I tweak this code to get the result sooner.
a=1
while True:
	n=0
	for y in range(1,21):
		if a%y==0:
			n=n+1
	if n==20:
		print(a)
		break
	else:
		a=a+1



RE: My code is taking longer time to give result - woooee - Feb-20-2019

> that is evenly divisible by all of the numbers from 1 to 20

That would be 20 by definition. Look at your assignment again. You have read it wrong.


RE: My code is taking longer time to give result - rajeshwin - Feb-20-2019

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?


RE: My code is taking longer time to give result - stranac - Feb-20-2019

The problem here is that you're trying to brute-force the solution by testing every number.
Since the solution is quite large, this will take some time.

Project Euler problems (which this is, even if you found it elsewhere) often require some clever optimization or specific mathematical knowledge.

In this case, you need to know how divisibility works, https://en.wikipedia.org/wiki/Divisibility_rule#Composite_divisors should be of help.
Once you do, you just need a single calculation to get a solution.


RE: My code is taking longer time to give result - ichabod801 - Feb-20-2019

Don't search for it, build it. Start with 1. 1 evenly divides into that. 2 does not, and there is no common divisor, so multiply by 2 to get 2. 3 does not evenly divide into 2, and there is no common divisor, so multiply by 3 to get 6. 4 does not divide into 6 evenly, but it has a common divisor of 2. So multiply 6 by (4 / 2) to get 12. Keep going up to 20.

You would need to build a greatest common divisor function, (or use the one in the math or fractions module), but then you can build it piece by piece rather than searching for it, which should be faster.