欧拉曾发表过一个著名的二次公式:
n² + n + 41
这个公式对于0到39的连续数字能够产生40个质数。但是当 n = 40时,402 + 40 + 41 = 40(40 + 1) + 41能够被41整除。当n = 41时, 41² + 41 + 41显然也能被41整除。
利用计算机,人们发现了一个惊人的公式:n² 79n + 1601。这个公式对于n = 0 到 79能够产生80个质数。这个公式的系数,79 和1601的乘积是126479。
考虑如下形式的二次公式:
n² + an + b, 其中| a| 1000, | b| 1000
其中| n| 表示 n 的绝对值。
例如, |11| = 11, | 4| = 4
对于能够为从0开始的连续的n产生最多数量的质数的二次公式,找出该公式的系数乘积。
public class Problem27
{
public static void main(String[] args)
{
long start = System.currentTimeMillis();
System.out.print("answer: ");
multi();
long end = System.currentTimeMillis();
System.out.print("time: ");
System.out.println(end - start);
}
static void multi()
{
int max = 0;
int answer = 0;
for (int i = -999; i < 1000; i++)
{
for (int j = 2; j < 1000; j++)
{
int had = 0;
for (int n = 1;; n++)
{
int m = n * n + i * n + j;
if (m < 0)
{
break;
}
if (check(m))
{
had++;
}
else
{
break;
}
}
if (max < had)
{
max = had;
answer = i * j;
}
}
}
System.out.println(answer);
}
static boolean check(int n)
{
for (int i = 2; i * i <= n; i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
}
answer: -59231
time: 83