LightOJ - 1197 Help Hanzo筛素数

本文介绍了一种用于找出指定范围内所有素数的算法。通过预先计算一部分素数,并使用这些素数来标记其倍数的方式,有效地找出[a, b]区间内的所有素数。这种方法特别适用于需要多次查询不同范围内的素数的情况。
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.


Sample Input
3
2 36
3 73
3 11
Sample Output
Case 1: 11
Case 2: 20
Case 3: 4
Note

A number is said to be prime if it is divisible by exactly two different integers. So, first few primes are 2, 3, 5, 7, 11, 13, 17, ...

题意是找a到b的素数有多少个。如果把所有的素数都筛出来的话内存会超,时间也会超。所以把前面的素数筛出来之后,再用素数去把他的倍数筛掉,用一个大小为b-a的数组标记。

#include<stack>
#include<queue>
#include<math.h>
#include<vector>
#include<string>
#include<stdio.h>
#include<map>
#include<iostream>
#include<string.h>
#include<algorithm>
#define maxn 1000005
#define maxm 10000005
#define MAXN 100005
#define MAXM 10005
#define mem(a,b) memset(a,b,sizeof(a))
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
bool vis[maxn+10];
bool vis1[maxn];
ll tot;
ll p[maxn];
void get_prime(){
     tot=0;
    mem(vis,true);
    for(ll i=2;i<=maxn;i++){
        if(vis[i]){
            p[tot++]=i;
            for(ll j=i*i;j<=maxn;j+=i)vis[j]=false;
        }
    }
}
int main(){
    get_prime();
    int t,test=0;
    scanf("%d",&t);
    while(t--){
        ll a,b;scanf("%lld%lld",&a,&b);
        ll ans=0;mem(vis1,false);
        for(int i=0;i<tot&&p[i]*p[i]<=b;i++){
            ll x=a/p[i]*p[i];if(x<=p[i])x=p[i]*2;
            for(ll j=x;j<=b;j+=p[i])if(j>=a)vis1[j-a]=true;
        }
        for(int i=0;i<=b-a;i++)if(!vis1[i]){ans++;}
        if(a==1)ans-=1;
        printf("Case %d: %lld\n",++test,ans);
    }
}


转载于:https://www.cnblogs.com/da-mei/p/9053219.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值