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 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 < 2^{31}, b - a ≤ 100000).

输出:

For each case, print the case number and the number of safe territories.

样例输入:

3

2 36

3 73

3 11

样例输出:

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 <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#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;//这里尽量把i和j定义成ll吧,因为后面的b是ll的,
                                          //如果 是int那就需要在i*i前面加(ll),否则会runtime
    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)//筛出[2,sqrt(b)]的素数
                isprime1[j]=1;
            for(ll j=max(2LL,(a+i-1)/i)*i;j<=b;j+=i)//筛出[a,b]的素数
                isprime2[j-a]=0;//这里的2LL是2的长整型数,与2LL比较的意思就是j最小是i的两倍
                                 //(a+i-1)/i表示的是[a,b]区间内的第一个数至少为i的多少倍.
        }
    }
    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--;//因为上面函数初始化的时候把所有的数都定义为素数,后来经过for循环
                        4,6,8....等数都成了false,但是1还是true,所以当a等于1的时候,
                          要减去1

        printf("Case %d: %d\n",ans++,res);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zhangjinlei321/article/details/82118846
今日推荐