【UVA 10200】Prime Time 素数打表 + 精度

  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

题意:就是给你一个区间,遍历区间的每一个数,通过一个函数 n^2 + n + 41 生成一个数,问你通过这个函数生成的素数的概率为多少,换句话说,有一个函数,定义域为一个区间内的整数,通过这个函数映射到一个集合,问你这个集合中素数的百分比。

题解:直接对区间[0,10000]生成的数进行打表来节省时间开销,我们直接用数组下标 i 来对应生成的那个数,因为这是等价的,如何快速判断一个数是不是素数呢,我们利用线性筛的额思想用小于这个数的平方根的素数去试除,如果试除到自己都还没除尽的,证明这个数是素数。但是这道题的坑在精度,这和double在计算机中的存储方式有关,所以我们直接在最后结果加上一个10的负8次方即可。

#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
const int maxn=110000+7;
bool isprime[10000+7];
ll a,b;
int prime[maxn];

void getprime()  //素数表
{
  memset(prime,0,sizeof(prime));
  for(int i=2;i<=maxn;i++){
    if(!prime[i]) prime[++prime[0]]=i;
    for(int j=1;j<=prime[0]&&(ll)prime[j]<=maxn/i;j++){
      prime[prime[j]*i]=1;
      if(i%prime[j]==0) break;
    }
  }
  return ;
}

bool judge(ll num)  // 快速判断一个数是不是素数
{
  for(int i=1;i<=prime[0];i++){
    if(num%prime[i]==0&&num!=prime[i]){
        return false;
    }
  }
  return true;
}

void init()  //对函数生成的数打表
{
  getprime();
  memset(isprime,false,sizeof(isprime));
  for(int i=0;i<=10000+1;i++){
    ll ans=i*i+i+41;
    if(judge(ans)) isprime[i]=true;
  }
    return ;
}

int main()
{
  init();
  while(scanf("%lld %lld",&a,&b)==2){
    int cnt=0;
    for(ll i=a;i<=b;i++){
      if(isprime[i]) cnt++;
    }
    printf("%.2f\n",double(cnt+0.00000001)/(b-a+1)*100);
  }
  return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值