Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

Tags:

python

What is wrong with my code? When i run the program nothing is printed. I want to print the smallest number that is evenly divisible by all of the numbers from 1 to 20.

found = False
i = 20
while found==False:
    c = 0    # c checks if the number is the one im looking for
    for x in range(1,21):
        if i%x==0:
            c = c + 1
    if c==20: # if c = 20 then its the number im looking for
        print i
        found = True
    i = i + 1    
like image 381
user3123012 Avatar asked Dec 09 '25 09:12

user3123012


2 Answers

Brute forcing this is WAY too slow. You need to find out what the prime factors of each number below 20 are, and then construct the smallest number that includes the same, and it will be the answer.

from collections import Counter

primes_below_20 = [2, 3, 5, 7, 11, 13, 17, 19]

def prime_factors(n):
    # Assume n <= 20 
    if n == 1:
        return []
    for prime in primes_below_20:
        if n % prime == 0:
            return [prime] + prime_factors(n / prime)

 primes_needed = Counter()

 for n in range(2, 21):
     primes = Counter(prime_factors(n))
     primes_needed = primes_needed | primes  # | gives the max of existing values

 total = 1
 for prime, amount in primes_needed.items():
     total *= prime ** amount

 print total
like image 98
RemcoGerlich Avatar answered Dec 11 '25 23:12

RemcoGerlich


Brute force:

from itertools import count
for i in count(20):
    if all(map(lambda x: i % x == 0, range(1, 21))):
        print i
        break

Non-brute-force:

from itertools import count, takewhile

def primes(n):
    "Generate prime numbers up to n"
    seen = list()
    for i in xrange(2, n + 1):
        if all(map(lambda prime: i % prime, seen)):
            seen.append(i)
            yield i

def smallest(n):
    result = 1
    for prime in primes(n):
        bprime = max(takewhile(lambda x:x<=n, (prime ** c for c in count(1))))
        # we could just take last instead of max()
        result *= bprime
    return result

print smallest(20)
like image 21
ondra Avatar answered Dec 11 '25 23:12

ondra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!