# Generating Quadratic Primes: Euler Problem 27

Prime numbers are the engine of the Internet economy becuse they cannot be generated through an algorithm. This impossibility has not stopped mathematicians from trying to find formulas to generate prime numbers. Euler problem 27 deals with quadratic formulas that can be used to generate sets of prime numbers. I have already discussed this in the article about the Ulam Spiral. This Numerphile video discusses quadratic primes.

## Euler Problem 27 Definition

Euler discovered the remarkable quadratic formula:

$n^2+n+41$

It turns out that the formula will produce 40 primes for the consecutive integer values $0 \leq n \leq 39$. However, when $n=40$, $40^2+40+41=40(40+1)+41$ is divisible by 41, and certainly when $n=41$, $41^2+41+41$ is clearly divisible by $41$.

The incredible formula $n^2-79n+1601$ was discovered, which produces 80 primes for the consecutive values $0 \leq n \leq 79$. The product of the coefficients, -79 and 1601, is -126479.

Considering quadratics of the form: $n^2+an+bn^2+an+b$,

where $|a| < 1000$ and $|b| \leq 1000$, where $|n|$ is the modulus/absolute value of $n$, e.g. $|11|=11$ and $|-4|=4$.

Find the product of the coefficients, $a$ and $b$, for the quadratic expression that produces the maximum number of primes for consecutive values of $n$, starting with $n=0$.

## Proposed Solution

The only way to solve this problem is through brute force and reduce the solution space to optimise it for speed (source: mathblog.dk). Because the outcome of the equation must be prime for $n = 0$, $b$ also has to be prime. We can use the prime sieve from Euler Problem 3, which reduces it from 2000 to 168 options. When we insert $n = 1$ it follows that a has to be an even number. If $1+a+b$ has to be prime and b has to be a prime number, then a can only be an odd number. However, when $b = 2 , a$, has to be even.

## Euler Problem 27 code

seq.a &lt;- seq(-999, 1001, 2) # a has to be odd
seq.b &lt;- (esieve(1000)) # b has to be prime
max.count &lt;- 0
for (a in seq.a) {
if (a == 2)
seq.a &lt;- seq(-1000, 1000, 2) # a has to be even
for (b in seq.b) {
n &lt;- 0 # Find sequence of primes for a and b
while (is.prime(n^2 + a * n + b)) {
n &lt;- n + 1 } # Store maximum values if (n &amp;gt; max.count) {
max.count &lt;- n
max.a &lt;- a
max.b &lt;- b
}
}
}