Problems 21 30

Euler 21: Evaluate the sum of all the amicable numbers under 10000

def euler21(end):
    condition = lambda pair: pair[0] < end and pair[1] < end
    return sum(flatten(takewhile(condition, amical_numbers(1))))

Euler 22: What is the total of all the name scores in the file of first names?

def euler22(data):
    clean = lambda s: s.replace('"', '').strip()
    points = dict((k, n+1) for n, k in enumerate(string.uppercase))
    names = sorted(imap(clean, data.split(",")))
    build_pair = lambda n, name: (name, (n+1)*sum(points[c] for c in name))
    pairs = starmap(build_pair, enumerate(names))
    return sum(value for name, value in pairs)

Euler 23: Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers

def check_perfect(num):
    """Return -1 if num is deficient, 0 if perfect, +1 if abundant"""
    return cmp(sum(get_divisors(num)[:-1]), num)
 
def euler23(limit):
    is_abundant = lambda x: check_perfect(x) == 1
    counter = lambda: xrange(1, limit+1)
    def getsums(lst):
        condition = lambda n: (n <= limit)
        getsum = lambda x, ix: takewhile(condition, (x+y for y in lst[ix:]))
        return (n for (ix, x) in enumerate(lst) for n in getsum(x, ix))
    set_difference = lambda x, y: set(x).difference(set(y))
    abundants = filter(is_abundant, counter())
    return sum(set_difference(counter(), getsums(abundants)))

Euler 24: What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?

def get_nth_permutation(n, lst):
    """Get nth element in permutations of elements from lst"""
    remove = lambda lst, toremove: [x for x in lst if x != toremove]
    if not lst:
        return []
    div, mod = divmod(n, factorial(len(lst)-1))
    element = lst[div]
    return [element]+get_nth_permutation(mod, remove(lst, element))
 
def euler24(n, lst):
    return "".join(map(str, get_nth_permutation(n-1, lst)))

Euler 25: What is the first term in the Fibonacci sequence to contain 1000 digits?

def fibonacci():
    """Generate fibonnacci serie"""
    next = lambda (a, b), _: (b, a+b)
    return (b for a, b in ireduce(next, count(), (0, 1)))
 
def euler25(ndigs):
    return iterlen(takewhile(lambda x: ndigits(x) < ndigs, fibonacci()))+1

Euler 26: Find the value of d<1000 for which 1/d contains the longest recurring cycle in its decimal fraction part

def euler26(end):    
    return max((get_decimals(1, num)[2], num) for num in xrange(2, end))[1]

Euler 27: Find a quadratic formula that produces the maximum number of primes for consecutive values of n

def get_decimals(num, div, current=([], [])):
    """Return a tuple (integer_part, decimal_part, cycle_length) for num/div"""
    headtail = lambda lst: (lst[0], lst[1:])
    memory, values = current
    if values and num == 0:
        integer, decimals = headtail(values)
        return integer, decimals, 0
    elif num in memory:
        integer, decimals = headtail(values)
        lencycle = len(memory) - memory.index(num)
        return integer, decimals, lencycle
    a, b = divmod(num, div)
    return get_decimals(10*b, div, (memory+[num], values+[a]))
 
def euler27(alst, blst):
    isprimec = memoize(isprime)
    fun = lambda a, b, n: n*n + a*n + b
    blstp = filter(lambda x: isprimec(x), blst)
    primeslen = lambda a, b: iterlen(takewhile(isprimec, \
        (fun(a, b, n) for n in count(0))))
    ma, mb = max((primeslen(a, b), (a, b)) for (a,b) in icross(alst, blstp))[1]
    return ma * mb

Euler 28: What is the sum of both diagonals in a 1001 by 1001 spiral formed in the same way?

def euler28(size):
    get_sums = lambda n: 4*(n**2) - 6*n + 6
    return 1+sum(get_sums(n) for n in xrange(3, size+1, 2))

Euler 29: How many distinct terms are in the sequence generated by a**b for 2 <= a <=100 and 2 <= b <= 100?

def euler29(alst, blst):
    return iterlen(unique(starmap(lambda a, b: a**b, icross(alst, blst))))

Euler 30: Find the sum of all the numbers that can be written as the sum of fifth powers of their digits"""

def euler30(npower):
    limit_condition = lambda n: ndigits(n*(9**npower)) > n
    limit = (9**npower)*last(takewhile(limit_condition, count(2)))
    getsum = lambda nums: sum(n**npower for n in nums)
    candidates = ((n, getsum(digsnum(n))) for n in xrange(10, limit+1))
    condition = lambda (x, y): (x==y)
    return sum(imap(operator.itemgetter(0), ifilter(condition, candidates)))
page_revision: 1, last_edited: 1186524943|%e %b %Y, %H:%M %Z (%O ago)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License