I’m trying to find the smallest number evenly divisible by each integer 1-20(inclusive). This is just me trying to improve on a practice exercise I had done before.
I wrote a function that takes in an argument and returns the smallest number that is evenly divisible by every positive integer smaller than the argument including itself but, it is not optimized and runs relatively slow as the numbers get larger.
I was wanting to know what would the Big-O notation be for this function and why. Then, if any, are there ways to speed this up, maybe with memoization I am not sure?
def divide_by_all(x):
## the 'pos' variable will be matched up against the argument to keep track of how many of the numbers in ##
## the arguments range are dividing evenly. ##
pos = 0
## the 'count' variable will be set to equal the input argument, possibly
count = x
## create the range of integers for the argument ##
divs = [i for i in range(1,x + 1)]
while pos != x:
for i in divs:
## check if each 'i' in the divs list is evenly divisible ##
## if 'i' is not evenly divisible the 'count'(answer) is incremented, the 'pos' is set back to zero to show ##
## the next 'count' has no evenly divisible in numbers div yet, and then loop over the divs list starts again ##
if count % i != 0:
count += 1
pos = 0
break
## if 'i' is evenly divides into current 'count' increment 'pos' ##
if count % i == 0:
pos += 1
## if 'pos' == the argument 'x', meaning every number in range(x) is evenly divisible ##
## return 'count' ##
if pos == x:
return count
Any tips and advice welcome!
It’s actually not that easy to give a good estimate of the asymptotic running time of this algorithm. As a ballpark estimate, it’s probably somewhat less than n! (i.e. VERY slow). The problem is simply that the answer grows quickly with n : it’s the product of the highest powers of the prime numbers less than n (for n=20, that would be 2^4 * 3^2 *5*7*11*13*17*19=232792560). As you check all numbers up to the answer, your running time is clearly greater than that (determining how much greater would take some work).
Memoization is not pertinent here as your alogorithm is not recursive.
Basically, this is a math problem, not an algorithmic one.