def problem60(limit=9000): primes = list(takewhile(lambda x: x < limit, get_primes())) primes.reverse() # we want to search smaller primes first from pop() # Use depth-first search. frontier = [[p] for p in primes] while frontier: node = frontier.pop() if len(node) == 5: return sum(node) for x in primes: child = node + [x] if x > max(node) and all_concat_to_prime(child): frontier.append(child)
def problem70(): # The search space is too large for brute-force. So, note that we are # seeking roughly the inverse of the previous problem -- to minimize # n/phi(n). Therefore, we want to maximize phi(n), which is acheived for # numbers with the fewest and largest unique prime factors. But the number # cannot simply be prime because in that case phi(n) == n-1 which is not a # permutation of n. Therefore, the best candidates should have two unique # prime factors. def is_permutation(x, y): return sorted(str(x)) == sorted(str(y)) # Since we are seeking large values for both prime factors, we can search # among numbers close to the value of sqrt(1e7) ~ 3162 ps = list(takewhile(lambda x: x < 4000, get_primes(start=2000))) ns = [x*y for x in ps for y in ps if x != y and x*y < 1e7] candidates = [n for n in ns if is_permutation(n, phi(n))] return min(candidates, key=lambda n: n/phi(n))
def problem51(): return next(filter(is_smallest_member, get_primes(start=56995)))
def candidates(): primes = get_primes() x = next(primes) while True: yield x x *= next(primes)