2

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)
3
  • 3
    Find a different algorithm. It won’t save you a lot of time by using a library in this case. Think about integer factorization and using prime numbers instead of just increasing a variable one every loop Commented Feb 22, 2021 at 18:58
  • 1
    At the very least, oper = 1 is a waste of time: all numbers are divisible by 1. Similarly, there's no point checking the odd numbers: none of them will be divisible by 2, let alone the larger even divisors. Start with num = 2, reset oper = 2 for each number, and increment num += 2. Commented Feb 22, 2021 at 18:59
  • 2
    You're looking for the least common multiple of your numbers. There are many algorithms to calculate it much more efficiently than your brute force way . Commented Feb 22, 2021 at 19:01

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

2 Comments

There's no need to make a copy of a.
@chepner is correct. For more context, he is speaking specifically on a[:], which should just be a.
1

you can do it using numpy:

import numpy as np
arr = np.arange(1,21)
t = np.lcm.reduce(arr)

also see these examples

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.