Problem
This problem comes from Project Euler 27
Problem
Euler discovered the remarkable quadratic formula:
It turns out that the formula will produce 40 primes for the consecutive integer values . However, when , is divisible by 41, and certainly when , is clearly divisible by 41.
The incredible formula was discovered, which produces 80 primes for the consecutive values . . The product of the coefficients, -79 and 1601, is -126 479.
Considering quadratics of the form:
,
where and
where is the modulus/absolute value of
e.g andFind the product of the coefficients, and , for the quadratic expression that produces the maximum number of primes for consecutive values of , starting with
Solution
The problem gives two example equations:
Where and , and
Where and
We should first notice that and for both equations are prime numbers. We should try creating these equations using prime numbers for and .
To solve the problem, I came up with the following steps:
- Create a list of positive primes and their negative counterparts
- For
a
, loop through the list containing the negative and positive primes - For
b
, loop through the list containing the positive primes - For
n
, try all numbers up to 1000 untiln
doesn’t produce a prime - Save the longest prime chain
Why does #3 use only positive primes? Actually, it doesn’t have to, but from observing the output, only the positive prime numbers produce chains, so we can do away with trying the negative side.
Code
# Project Euler: Problem 27
# Quadratic Primes
from PEF import soe
max_a = 0
max_b = 0
max_count = 0
p_primes = soe(1000)
n_primes = [-p for p in p_primes]
primes = n_primes + p_primes
for a in primes:
for b in p_primes:
prime_count = 0
for n in range(1001):
if n*(n+a)+b in p_primes:
prime_count += 1
if prime_count > max_count:
max_a = a
max_b = b
max_count = prime_count
else:
break
print(max_a*max_b)
p_primes
means “positive primes”n_primes
means “negative primes”soe()
is the Sieve of Eratosthenes, a prime number sieve written in Problem 3