113C - Double Happiness 求區間%4=1的素數--可以表示成平方和的形式--的個數(素數篩選法)

On the math lesson a teacher asked each pupil to come up with his own lucky numbers. As a fan of number theory Peter chose prime numbers. Bob was more original. He said that number t is his lucky number, if it can be represented as:

t = a2 + b2, 
where a, b are arbitrary positive integers.

Now, the boys decided to find out how many days of the interval [l, r] (l ≤ r) are suitable for pair programming. They decided that the day i (l ≤ i ≤ r) is suitable for pair programming if and only if the number i is lucky for Peter and lucky for Bob at the same time. Help the boys to find the number of such days.

Input

The first line of the input contains integer numbers l, r (1 ≤ l, r ≤ 3·108).

Output

In the only line print the number of days on the segment [l, r], which are lucky for Peter and Bob at the same time.

Sample test(s)
input
3 5
output
1
input
6 66
output
7


//

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=300000000;
bool flag[maxn/4+10];
int prime[20000],vs[20000],pl;
void _prime(int n)
{
    for(int i=2;i<=n;i++)
    {
        if(!vs[i]) prime[pl++]=i;
        for(int j=0;j<pl&&i*prime[j]<=n;j++)
        {
            vs[i*prime[j]]=1;
            if(i%prime[j]==0) break;
        }
    }
}
int initprime(int l,int r)
{
    int ans=0;
    if(l<=2&&r>=2) ans++;
    while(l%4!=1||l==1) l++;
    int sqt=(int)sqrt(0.5+r);
    _prime(sqt);
    for(int i=0;i<pl;i++)
    {
        int g=l/prime[i];
        if(g<2) g=2;
        int j=g*prime[i];
        for(;j<=r;j+=prime[i])
        {
            if(j%4==1)//將%4=1的合數刪去,剩下的就是%4=1的素數
            {
                flag[j>>2]=1;
            }
        }
    }
    for(int i=l;i<=r;i+=4)
    {
        if(!flag[i>>2]) ans++;
    }
    return ans;
}
int main()
{
    int l,r;
    scanf("%d%d",&l,&r);
    int ans=initprime(l,r);
    printf("%d\n",ans);
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章