""" Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. """ from itertools import takewhile from common import elapsed from seq import fib limit = 4000000 total = sum( takewhile(lambda x: x <= limit, filter(lambda x: x % 2 == 0, fib()))) print("Sum of even fibonnaci numbers up to {}: {}".format(limit, total)) elapsed()
def solve_by_pairing(target_size=target_set_size): # This algorithm will populate prime_pairs with each prime (key) pointing to a set of all # smaller primes that form a valid prime pair with it. # Each of these is then checked by get_connected_set to see if there are enough pairwise # connections to complete the problem. # NOTE: prime index starts from 3 to avoid primes 2 and 5, which cannot be part of any prime pair. # 3 is chained into the inner loop, but not the outer loop because no valid primes are less than 3. log_step = 1000 next_step = 0 for p in primes(step=10000, start_index=3): for q in chain(reversed(sieve_primes(max_prime=p)[3:-1]), [3]): populate_prime_pairs(p, q) if p > next_step: split_timer() print(f"Reached p > {next_step} -- {p}: {prime_pairs.get(p)}") next_step += log_step if p in prime_pairs: p_set = get_connected_set(prime_pairs[p], target_size - 1) if p_set: p_set.add(p) return sorted(p_set)[:target_size] print(solve_by_pairing(5)) elapsed() # Around 20 minutes!