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)

Sunday, December 1, 2013

Solution to Project Euler problem number 4 in Python

Solution

def reverse(number):
    result = 0
    while number > 0:
        result = result * 10 + (number % 10)
        number = int(number / 10)
    return result

def is_palindrome(number):
    return number == reverse(number)

largestPalindrome = 0
a = 999
while a >= 100:
    if a % 11 == 0:
        b = 999
        db = 1
    else:
        b = 990
        db = 11 
    while b >= a:
        if a*b <= largestPalindrome:
            break
        if is_palindrome(a*b):
            largestPalindrome = a*b
            b = b-db
        a = a-1
print largestPalindrome