the question of project euler #5 is: 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?
result=1
done=False
while not done:
result+=1
for x in range(2,21):
if result%x!=0:
break
elif x==20:
done=True
print(result)
but it takes too long time when it runs. well, it seems that this code doesn't work. what is the problem in this code?
Because it has to be divided by 20
so you can check only multiples of 20
- this way you have to check a lot less numbers.
If number is divided by 20
so it has to be divided by 2
, 10
(20=2*10
), 4
, 5
(20=4*5
) so you don't have to check for 2
,4
,5
,10
. The same way you can eliminate other numbers.
Finally I got list 20
, 19
, 18
, 17
, 16
, 15
, 14
, 13
, 11
import time
start = time.time()
result = 0
done = False
while not done:
result += 20
for x in [20, 19, 18, 17, 16, 15, 14, 13, 11]:
if result % x != 0:
break
else:
done = True
end = time.time()
print('result:', result)
print('time in seconds:', end-start)
Result:
result: 232792560
time in seconds: 6.6211323738098145
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments