Sunday 5 May 2019

Project Euler 146 - Investigating a Prime Pattern

Investigating a Prime Pattern

Problem 146

The smallest positive integer n for which the numbers n2+1, n2+3, n2+7, n2+9, n2+13, and n2+27 are consecutive primes is 10. The sum of all such integers n below one-million is 1242490.
What is the sum of all such integers n below 150 million?



Well, the key was to find a good algorithm to test prime number.

import time
import sympy

now = time.time()
result = []
for n in range (10, 150000001, 10):
    if n ** 2 % 3 == 1 and n ** 2 % 7 == 2 and n ** 2 % 13 != 0 and sympy.isprime(n ** 2 + 1) and sympy.isprime(n ** 2 + 3) and sympy.isprime(n ** 2 + 7) and sympy.isprime(n ** 2 + 9) and sympy.isprime(n ** 2 + 13) and sympy.isprime(n ** 2 + 27) \
            and not sympy.isprime(n ** 2 + 23) and not sympy.isprime(n ** 2 + 21) and not sympy.isprime(n ** 2 + 19) and not sympy.isprime(n ** 2 + 17):
        result.append(n)
        print(n)
print ('result=', sum(result))
print('time spent is {}'.format(time.time() - now))