Tuesday, December 3, 2013

Python solution to Project Euler problem number 5

Solution

def is_prime(x, primes):
    for p in primes:
        if x % p == 0:
            return False
    return True

assert is_prime(3, [2])
assert not is_prime(4, [2, 3])

def smallest_common_multiple_of_all_numbers_up_to(x):
    if x == 1:
        return 1
    y = 1
    primes = []
    for i in range(2, x + 1):
        if is_prime(i, primes):
            primes.append(i)
            y *= i
            continue
        if y % i == 0:
            continue
        for p in primes:
            if (y * p) % i == 0:
                y *= p
                break
    return y

assert smallest_common_multiple_of_all_numbers_up_to(3) == 6
assert smallest_common_multiple_of_all_numbers_up_to(10) == 2520

print smallest_common_multiple_of_all_numbers_up_to(20)

No comments: