Prime Time UVA - 10200 (打表+高精度陷阱)

Euler is a well-known matematician, and, among many other things, he discovered that the formulan2+n+ 41 produces a prime for 0n<40. Forn= 40, the formula produces 1681, which is 4141.Even though this formula doesn’t always produce a prime, it still produces a lot of primes. It’s knownthat forn10000000, 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 integeraandbsuch that 0ab10000. You mustread until the end of the le.

Output

For each paira,bread, you must output the percentage of prime numbers produced by the formula inthis interval (anb) rounded to two decimal digits.

Sample Input

0 39
0 40
39 40

Sample Output

100.00
97.56
50.00

题意:

求输入所给范围内的数经过题目要求的变化后的数的素数百分比。

思路:
题中所给数据不大于10000,先找出1到10000之间经过变形后的素数,将
这些素数以下标的形式标记,再经过for循环找出从0到10000内的素数个数,使下面找输入数据范围内的素数个数更快速容易,最后加1e-8是因为精度问题,这是个非常非常大的坑!!这个题精度属实很高!!

代码:

#include<stdio.h>
#include<math.h>
int s[10010];
void prime()
{
    s[0]=1;
    int i,j;
    long long n;
    for(i=1; i<10000; i++)
    {
        int flag=0;
        n=i*i+i+41;
        for(j=2; j<=(int)sqrt(n); j++)
        {
            if(n%j==0)
                //flag=1;       //斜杠这些是另一种标记素数的方法 
            break;

        }
        if(j==(int)sqrt(n)+1)
                s[i]=1;
        //if(flag==0)
            //s[i]=1;
    }
    for(i=0; i<=10000; i++)
        s[i]=s[i]+s[i-1];
}
int main()
{
    int a,b,s1;
    prime();
    while(scanf("%d%d",&a,&b)!=EOF)
    {
        s1=s[b]-s[a-1];
        printf("%.2f\n",(s1*1.0)/(b-a+1)*100+1e-8);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Piink/article/details/105300979