题目链接
题意:
有许多素数可以写成nn+n+41的形式,给定n的范围[a,b], 求[a, b]内nn+n+41是素数的概率。
思路:
素数打表,遍历[a, b]记录n*n+n+41是素数的个数, 再除以[a, b]中数的总个数;最后输出需要加1e-5, 不然会WA
#include<cstdio>
#include<cstring>
using namespace std;
const int Max = 1e8 + 1e5;
bool IsPrime[Max];
void Sieve()
{
memset(IsPrime, 1, sizeof(IsPrime));
IsPrime[0]=IsPrime[1]=0;
for(long long i=2; i<=Max; i++)
{
if(IsPrime[i])
{
for(long long j=i*i; j<=Max; j+=i)
{
IsPrime[j]=0;
}
}
}
}
int main()
{
int a, b, cnt;
double ans;
Sieve();
while(~scanf("%d%d", &a, &b))
{
cnt = 0;
for(int i=a; i<=b; i++)
{
if(IsPrime[i*i+i+41])
cnt++;
}
ans = (cnt*1.0)/(1.0*(b-a+1));
printf("%.2f\n", ans*100+1e-5);
}
return 0;
}