Source
Problem
輸入4個正整數 ,輸出區間 內距離爲 的素數 元組的個數。
Solution
最大爲 ,只要篩選 以內的素數。然後每次把在 內的素數找出來。一開始用 開到45000,在UVA上以13秒的時間過了,但在UVALive上TLE了。然後把 加到 ,在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;
}