Project Euler Problem 27 Quadratic primes

Quadratic primes

Problem 27

Euler discovered the remarkable quadratic formula:

n2+n+41

It turns out that the formula will produce 40 primes for the consecutive integer values 0n39

. However, when n=40,402+40+41=40(40+1)+41 is divisible by 41, and certainly when n=41,412+41+41

is clearly divisible by 41.

The incredible formula n279n+1601

was discovered, which produces 80 primes for the consecutive values 0n79

. The product of the coefficients, −79 and 1601, is −126479.

Considering quadratics of the form:

n2+an+b

, where |a|<1000     and |b|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.


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;
}



posted on 2017-03-30 19:47  海岛Blog  阅读(143)  评论(0编辑  收藏  举报

导航