def euler_14(): """Find the longest sequence using a starting number under one million.""" lengths = {} def sequence(n): m = n length = 1 while m != 1: if m in lengths: length += lengths[m] break if m % 2 == 0: m = m / 2 else: m = 3 * m + 1 length += 1 lengths[n] = length return length max_length, max_n = 0, 1 for n in range(1, 1000000): length = sequence(n) if length > max_length: max_length = length max_n = n return max_n
def euler_27(): "Find a quadratic formula that produces the maximum number of primes for consecutive values of n." from itertools import chain, imap, product, takewhile, tee from eutil import ilen, primes, is_prime, sequence a_s = xrange(-999, 1000) ps = tee(takewhile(lambda p: p < 1000, primes())) b_s = chain(ps[0], imap(lambda x: -x, ps[1])) seqs = [(ilen(takewhile(is_prime, sequence(lambda n: n ** 2 + a * n + b))), a, b) for a, b in product(a_s, b_s)] seq = max(seqs, key=lambda t: t[0]) return seq[1] * seq[2]
def euler_65(): """Find the sum of digits in the numerator of the 100th convergent of the continued fraction for e.""" from eutil import nth, digits def sequence(): num = [] t = 0 while True: if t == 0: num.append(1) elif t == 1: num.append(2) else: coef = t / 3 * 2 if t % 3 == 0 else 1 num.append(coef * num[t - 1] + num[t - 2]) yield num[-1] t += 1 return sum(digits(nth(sequence(), 100)))