Source
Problem
输入4个正整数 a,b,k,s a , b , k , s ,输出区间 [a,b] [ a , b ] 内距离为 s s 的素数元组的个数。
Solution
b b 最大为,只要筛选 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 加到 2∗107 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;
}