LightOj 1197 数论基础(求素数打表进阶)Help Hanzo

博客围绕解决Hanzo通过领地时安全领地计数问题展开。已知领地编号范围,其中质数编号领地安全,需根据输入的范围计算安全领地数量。提到用两个筛解决问题,普通写法会内存不够。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码如下

改的时间太久了心态爆炸,两个筛就行了,普通写内存不够

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;
 }
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Randy__Lambert

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值