Help Hanzo

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.

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,求a,b之间的素数个数

思路

b以内的合数的最小质因数一定不超过sqrt(b)。我们可以先打出【2,sqrt(b)】和【a,b】的表,从[2,sqrt(b))的表中筛得素数的同时,也将其倍数从[a,b)的表中划去,最后剩下的就是区间[a,b)内的素数了

#include<queue>
#include<math.h>
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn= 1e5+10;
#define ll long long
bool isprime1[maxn],isprime2[maxn];
int  sieve(ll a,ll b)
{
    for(ll i=0; i*i<=b; i++) isprime1[i]=0;
    for(ll i=0; i<=b-a; i++) isprime2[i]=1;
    for(ll  i=2; i*i<=b; i++)
    {
        if(!isprime1[i])
        {
            for(ll j=i+i; j*j<=b; j+=i)
                isprime1[j]=1;
            for(ll j=max(2LL,(a+i-1)/i)*i; j<=b; j+=i)
                isprime2[j-a]=0;
        }
    }
    int sum=0;
    for(int i=0; i<=b-a; i++)
        if(isprime2[i])sum++;
    return sum;
}
int main()
{
    ll a,b;
    int t;
    int ans=1;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%lld%lld",&a,&b);
        int res=sieve(a,b);
        if(a==1)res--;
        printf("Case %d: %d\n",ans++,res);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值