Prime Time 素数筛选+玄学1e-8

来源:互联网 发布:三菱fxplc编程手册 编辑:程序博客网 时间:2024/05/29 19:40
Euler is a well-known matematician, and, among many other things, he discovered that the formula
n
2 + 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 known
that 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 certain
interval.
Input
Each line of input will be given two positive integer a and b such that 0 ≤ a ≤ b ≤ 10000. You must
read 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 in
this 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

题意:

这是一道非常简单的题,0<=a<=n<=b<=10000,求区间内n的公式n*n+n+41组成的素数所占的比例

注意:素数打表,先提前统计tot的值,再给ans[tot]开大小,不然会炸。

然后就是结果加1e-8,是一个非常小的double型数据,据说是防止精度损失,不加就错,记住就好

#include<cstdio>#include<cstring>using namespace std;const int N=100020000;bool v[N];int tot=0,ans[6000000];void Prime(){    memset(v,true,sizeof(v));    for(int i=2;i<N;++i)    {        if(v[i]) ans[tot++]=i;        for(int j=0;(j<tot)&&(i*ans[j]<N);++j)        {            v[i*ans[j]]=false;            if(i%ans[j]==0) break;        }    }}int main(){    Prime();    int a,b;    while(~scanf("%d%d",&a,&b))    {        int cnt=0;        for(int i=a;i<=b;++i)            if(v[i*i+i+41]) cnt++;        double ans=cnt*1.0/(b-a+1)*100;        printf("%.2f\n",ans+1e-8);    }    return 0;}