Euler is a well-known matematician, and, among many other things, he discovered that the formula n2 + n + 41 produces a prime for 0 ≤ n < 40. For n = 40, the formula produces 1681, which is 41 ∗ 41.Even though this formula doesn’t always produce a prime, it still produces a lot of primes. It’s knownthat for n ≤ 10000000, there are 47,5% of primes produced by the formula!
So, you’ll write a program that will output how many primes does the formula output for a certaininterval.
Input
Each line of input will be given two positive integer a and b such that 0 ≤ a ≤ b ≤ 10000. You mustread until the end of the file.
Output
For each pair a, b read, you must output the percentage of prime numbers produced by the formula inthis interval (a ≤ n ≤ b) rounded to two decimal digits.
Sample Input
0 39
0 40
39 40
Sample Output
100.00
97.56
50.00
问题链接:UVA10200 Prime Time
问题简述:根据公式n * n + n + 41 求出在区间a<= n <= b的n算出的结果是素数的概率。0<= a <= b <= 10000。
问题分析:
统计各个范围的素数的个数是必要的,然后再进行计算。
n=0时,41是素数。
要算区间的概率,需要先计算前缀和,即计算给定n的1-n之间的素数的个数。这样就容易算得区间内的素数个数。
程序说明:
数组sum[]中,存放素数个数的前缀和。sum[i]中存放从0-i之间,满足公式i * i + i + 41为素数的个数。
函数isprime()不是一个真正意义上的素数判断函数,只进行奇数判定,对于本题条件是没有问题的,因为n*n+n+41总是奇数。
函数maketable()是打表函数,用于计算数组sum[]的值。
AC的C++语言程序如下:
/* UVA10200 Prime Time */
#include <iostream>
#include <math.h>
using namespace std;
const int N = 10000;
int sum[N + 1];
// 试除法判断一个数是否为素数
bool isprime(int n)
{
int end2, i;
end2 = (int)sqrt(n);
for(i=3; i<=end2; i+=2) {
if(n % i == 0)
break;
}
return i > end2;
}
void make_table()
{
sum[0] = 1;
for(int i=1; i<=N; i++) {
sum[i] = sum[i - 1];
if(isprime(i * i + i + 41))
sum[i]++;
}
}
int main()
{
int a, b, cnt;
double ans;
make_table();
while(scanf("%d%d", &a, &b) != EOF) {
if(a == 0)
cnt = sum[b];
else
cnt = sum[b] - sum[a - 1];
ans = (double) cnt / (b - a + 1);
printf("%.2lf\n", ans * 100 + 1e-5);
}
return 0;
}