代码如下
改的时间太久了心态爆炸,两个筛就行了,普通写内存不够
Help Hanzo
Amakusa, the evil spiritual leader has captured the beautiful princess Nakururu. The reason behind this is he had a little problem with Hanzo Hattori, the best ninja and the love of Nakururu. After hearing the news Hanzo got extremely angry. But he is clever and smart, so, he kept himself cool and made a plan to face Amakusa.
Before reaching Amakusa’s castle, Hanzo has to pass some territories. The territories are numbered as a, a+1, a+2, a+3 … b. But not all the territories are safe for Hanzo because there can be other fighters waiting for him. Actually he is not afraid of them, but as he is facing Amakusa, he has to save his stamina as much as possible.
He calculated that the territories which are primes are safe for him. Now given a and b he needs to know how many territories are safe for him. But he is busy with other plans, so he hired you to solve this small problem!
input
Input starts with an integer T (≤ 200), denoting the number of test cases.
Each case contains a line containing two integers a and b (1 ≤ a ≤ b < 231, b - a ≤ 100000).
output
For each case, print the case number and the number of safe territories.
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
bool a[1100000];
long long int b[50005];
int main(){
int n,ci = 0;
memset(a,1,sizeof(a));
a[0] = a[1] = 0;
for(int i = 2;i < 50005;i++){
if(a[i]) b[ci++] = i;
for(int j = 0;j < ci&&b[j]*i<50005;j++){
a[b[j]*i] = 0;
if(i%b[j] == 0) break;
}
}//欧拉筛法,不要太大,大于sqrt(x)后面的就没意义了,反而会是这道题超时
scanf("%d",&n);
long long x,y,bb;
for(int k = 1;k <= n;k++){
long long int sum = 0;
scanf("%lld%lld",&x,&y);
memset(a,1,sizeof(a));
for(long long int i = 0;i < ci;i++){
bb = x/b[i];//以下三行关键步骤,求出比x大的,还恰好是上面筛出质数表中的质数的倍数
while(bb*b[i]<x||bb<=1) //例如设x = 20 ,此时筛的质数为3,则从大于x小于y的中3最小的倍数开始进行筛
bb++; //筛去21,24,27.。。。虽然这筛的时候会重复筛某个元素,但是对于此题并不会超时
for(long long int j = bb*b[i];j <= y;j+=b[i] ){
if(j>=x){
a[j-x]=0;
}
}
}
for(int i=0; i<=y-x ;i++)
if(a[i]) sum++;
if(x!=1)
printf("Case %d: %lld\n",k,sum);//特判当a == 1
if(x==1)
printf("Case %d: %lld\n",k,sum - 1);
}
return 0;
}