Someone asked about this question on the main StackOverflow. The full question is:
Given a value N, find
psuch that all of
[p, p + 4, p + 6, p + 10, p + 12, p + 16]are prime.
- The sum of
[p, p + 4, p + 6, p + 10, p + 12, p + 16]should be at least N.
My thinking is:
- Sieve all primes under N
- Ignore primes below
- Create consecutive slices of length 6 for the remaining primes.
- Check if the slice matches the pattern.
Here's my solution. I'd appreciate some feedback.
from itertools import dropwhile, islice def get_solutions(n): grid = [None for _ in range(n+1)] i = 2 while i < n+1: if grid[i] is None: grid[i] = True for p in range(2*i, n+1, i): grid[p] = False else: i += 1 sieve = (index for index, b in enumerate(grid) if b) min_value = (n - 48) / 6 reduced_sieve = dropwhile(lambda v: v < min_value, sieve) reference_slice = list(islice(reduced_sieve, 6)) while True: try: ref = reference_slice differences = [v - ref for v in reference_slice[1:]] if differences == [4, 6, 10, 12, 16]: yield reference_slice reference_slice = reference_slice[1:] + [next(reduced_sieve)] except StopIteration: break n = 2000000 print(next(get_solutions(n))) # or for all solutions for solution in get_solutions(n): print(solution)