what is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? in python

One efficient way to solve this problem is by finding the prime factors for each number from 1 to 20, then multiplying the highest power of each prime factor together to get the solution. Here's an implementation in Python:

main.py
def smallest_multiple(n):
    prime_factors = {}  # dictionary to store prime factors and their highest powers
    for i in range(2, n+1):
        num = i
        for j in range(2, i+1):
            count = 0
            while num % j == 0:
                count += 1
                num //= j
            if count > 0:
                prime_factors[j] = max(count, prime_factors.get(j, 0))
    result = 1
    for prime, power in prime_factors.items():
        result *= prime ** power
    return result
504 chars
16 lines

This function takes an input n and returns the smallest positive number that is evenly divisible by all numbers from 1 to n. Here's how to use it:

main.py
>>> smallest_multiple(10)
2520
>>> smallest_multiple(20)
232792560
67 chars
5 lines

The first call finds the smallest multiple of all numbers from 1 to 10, which is 2520. The second call finds the smallest multiple of all numbers from 1 to 20, which is 232792560.

gistlibby LogSnag