Quadratic primes
Problem 27
Euler discovered the remarkable quadratic formula:
n2+n+41 n2+n+41
It turns out that the formula will produce 40 primes for the consecutive integer values 0≤n≤39 0≤n≤39. However, when n=40,402+40+41=40(40+1)+41 n=40,402+40+41=40(40+1)+41 is divisible by 41, and certainly when n=41,412+41+41 n=41,412+41+41 is clearly divisible by 41.
The incredible formula n2−79n+1601 n2−79n+1601 was discovered, which produces 80 primes for the consecutive values 0≤n≤79 0≤n≤79. The product of the coefficients, −79 and 1601, is −126479.
Considering quadratics of the form:
n2+an+b n2+an+b, where |a|<1000 |a|<1000 and |b|≤1000 |b|≤1000
where |n| |n| is the modulus/absolute value of n n
e.g. |11|=11 |11|=11 and |−4|=4 |−4|=4
Find the product of the coefficients, a a and b b, for the quadratic expression that produces the maximum number of primes for consecutive values of n n, starting with n=0 n=0.
题意:二次质数。欧拉发现了著名的二次方程:n² + n + 41。当n=0~39时,这个方程能够连续产生40个质数。但是,当n=40时,402 + 40 + 41 = 40(40 + 1) + 41可以被41整除,当然,还有当n = 41, 41² + 41 + 41 可以被41整除。
发现了更奇妙的方程: n² – 79n + 1601,当n=1~79时,它能够 连续产生80个质数。方程系数的积为 –79 * 1601 = -126479.
考虑二次方程的形式:
n² + an + b, |a| < 1000 且 |b| < 1000
|n| 是n 的绝对值。
找到系数a和b,当n从0开始连续递增时,可以产生最多的质数。给出a*b的值。
暴力枚举吧....
代码:
#include<bits/stdc++.h>
using namespace std;
int isprime(int n)
{
if (n<=1)return 0;
for(int i=2;i<=sqrt(n);i++)
if(n%i==0)return 0;
return 1;
}
int gao(int a, int b) //连续素数的个数
{
int cnt = 0;
for (int i=0;;i++)
{
if (isprime(i*i+a*i+b)) //二元产生的是素数
{
cnt++;
}
else break;
}
return cnt;
}
int main()
{
int maxa,maxb,maxprimes=0;
for (int a=-1000;a<1000;a++)
{
for(int b=-1000;b<1000;b++)
{
if(gao(a,b)>maxprimes)
{
maxa = a;
maxb = b;
maxprimes = gao(a,b);
}
}
}
cout<<maxa*maxb<<endl;
return 0;
}