UVAlive3998 (UVA 1404) Prime k-tuple (素数筛法)

Source

Problem

输入4个正整数 a,b,k,s a , b , k , s ,输出区间 [a,b] [ a , b ] 内距离为 s s 的素数k元组的个数。

Solution

b b 最大为maxn=2109,只要筛选 SIZE=maxn S I Z E = m a x n 以内的素数。然后每次把在 [a,b] [ a , b ] 内的素数找出来。一开始用 SIZE S I Z E 开到45000,在UVA上以13秒的时间过了,但在UVALive上TLE了。然后把 SIZE S I Z E 加到 2107 2 ∗ 10 7 ,在UVALive上以19.5s勉强通过。最后改了函数,快了十倍不止。

Code

  • 蜗速代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int t,a,b,k,s;
const int SIZE=2e7+10;

bool isComp[SIZE] = {false};
int P[SIZE] = {0};
int PCnt = 0;
void sieve(){
  for(int i=2;i<SIZE;++i){
    if ( !isComp[i] ) P[PCnt++] = i;

    for(int j=0;j<PCnt&&i*P[j]<SIZE;++j){
       isComp[i*P[j]] = true;
       if ( 0 == i % P[j] ) break;
    }
  }
}

bool isPrime(int x){
    if ( x < SIZE ) return !isComp[x];

    for(int i=0;P[i]*P[i]<=x&&i<PCnt;++i)
        if ( 0 == x % P[i] )
            return false;
   return true;
}

int main()
{
    sieve();
    scanf("%d",&t);
    while(t--)
    {
        int ans=0;
        vector<int> pr;
        scanf("%d%d%d%d",&a,&b,&k,&s);
        for(int i=a;i<=b;++i)
            if(isPrime(i))
                pr.push_back(i);
        int len=pr.size();
        for(int i=0;i+k-1<len;++i)
            if(pr[i+k-1]-pr[i]==s)
                ++ans;
        printf("%d\n",ans);
    }
    return 0;
}
  • 光速代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int t,a,b,k,s;
const int SIZE=2e7+10;
bool isComp[SIZE] = {false};
int P[SIZE] = {0},c[SIZE];
int PCnt = 0;

void sieve(){
  for(int i=2;i<SIZE;++i){
    if ( !isComp[i] ) P[PCnt++] = i;

    for(int j=0;j<PCnt&&i*P[j]<SIZE;++j){
       isComp[i*P[j]] = true;
       if ( 0 == i % P[j] ) break;
    }
  }
}

int solve(int a,int b,int k,int s)
{
    if(a>b) return 0;
    int cnt=0,ans=0;
    memset(isComp,0,sizeof(isComp));
    for(int i=0;P[i]*P[i]<=b;++i)
    {
        int w=P[i];
        for(int j=max(2,(a+w-1)/w)*w;j<=b;j+=w)
            isComp[j-a]=1;
    }
    for(int i=a;i<=b;++i)
        if(!isComp[i-a]) c[cnt++]=i;
    for(int i=0;i<=cnt-k;++i)
        if(c[i+k-1]-c[i]==s) ++ans;
    return ans;
}
int main()
{
    sieve();
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d%d%d",&a,&b,&k,&s);
        int ans=solve(a,b,k,s);
        printf("%d\n",ans);
    }
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值