Reputation: 115
I am trying to make a script that figures out the least number divisible by numbers from 1 to 20 without any remainder. Apparently it works well with finding the least number that can be divided from 1 to 10 which is 2520, but for the former problem it takes a lot of time to actually find it because the number is much bigger than 2520 (232792560). So is there anyway to make that process faster, I am totally new to Python by the way. Here is the code I used:
num = 1
oper = 1
while oper <= 20:
y = num % oper
if y == 0:
oper += 1
else:
num += 1
oper = 1
print(num)
Upvotes: 2
Views: 129
Reputation: 3545
you can do it using numpy:
import numpy as np
arr = np.arange(1,21)
t = np.lcm.reduce(arr)
also see these examples
Upvotes: 1
Reputation: 634
from math import gcd
a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
lcm = a[0]
for i in a:
lcm = lcm*i//gcd(lcm, i)
print(lcm)
Your algorithm is quite slow and will not work for quite large numbers efficiently. This will find the lcm for each number and multiply it to the previous number.
Upvotes: 1