Project Euler Problem 27 Quadratic primes
Problem 27
Euler discovered the remarkable quadratic formula:
It turns out that the formula will produce 40 primes for the consecutive integer values
. However, 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 −126479.
Considering quadratics of the form:
n2+an+b
, where
where
is the modulus/absolute value of
e.g.
Find the product of the coefficients,
and
C++:
#include <iostream> #include <cmath> using namespace std; const int N = 1000; bool isprime(int n) { if(n == 1) return false; if(n == 2) return true; if(n % 2 == 0) return false; int end = sqrt(n); for(long i=3; i<=end; i+=2) if(n % i == 0) return false; return true; } int main() { int ans, maxn=0, n, expr; for(int b=1; b<N; b++) if(isprime(b)) { for(int a=-b; a<N; a++) { n = 0; expr = n * n + a * n + b; while(expr > 0 && isprime(expr)) { n++; expr = n * n + a * n + b; } if(n > maxn) { maxn = n; ans = a * b; } } } cout << ans << endl; return 0; }