Double Happiness
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*10^8).
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
题目大意:
给定区间[L,R],求区间内满足条件的数的个数:
条件1)z是素数
条件2)z=x^2+y^2 x和y为任意的正整数
结题思路:
其实就是求满足费马定理的数的个数。
费马定理:一个奇素数z可以表示成z=x^2+y^2的形式,当且仅当z可以表示成4*t+1的时候。(偶素数2=1^2+1^2)
LR的范围是1到3*10^8用普通的筛选法求素数表,时间空间都会超。使用两次筛选来求素数。
3*10^8的平方根小于17500,用17500以内的素数可以筛出范围内的所有素数。在通过判断是否满足z=t%4+1来累加。
又由于z的范围过大,但对于唯一确定的z来说,t也唯一确定,故可以用t作为数组下标即(z-1)/4。数组大小就会小4倍左右。
具体细节看代码备注。
Code:
1 #include <algorithm> 2 #include <iostream> 3 #include <cstdlib> 4 #include <cstring> 5 #include <cstdio> 6 #include <string> 7 #include <bitset> 8 #define MAXN 17500 9 using namespace std; 10 bitset<MAXN>ISP; //类似于bool型,可以存01 11 bitset<300000000/4+10>result; 12 int prime[MAXN]; 13 int is_prime()//先筛选1-17500的素数 14 { 15 int p=0; 16 ISP[0]=ISP[1]=1; 17 for (int i=1; i<=MAXN; i++) 18 if (ISP[i]==0) 19 { 20 prime[p++]=i;//用prime素组将素数存起来留到后面筛选用。。 21 for (int j=i+i; j<=MAXN; j+=i) 22 ISP[j]=1; 23 } 24 return p-1; 25 } 26 int cnt(int L,int R) 27 { 28 int p=is_prime(); 29 for (int j=0; j<=p; j++) 30 { 31 int x=L/prime[j]; 32 if (x*prime[j]<L) x++; 33 if (x==1) x++; 34 for (int k=x*prime[j]; k<=R; k+=prime[j]) //通过素数表再来筛选[L,R]中的素数 35 if (k%4==1) //标记符合条件2且不符合条件1的数 36 result[(k-1)/4]=1; 37 } 38 int cnt=0; 39 for (int i=L;i<=R;i+=4) 40 if (!result[(i-1)/4]) cnt++; 41 return cnt; 42 } 43 int main() 44 { 45 is_prime(); 46 int L,R; 47 int ok=0; 48 cin>>L>>R; 49 if (L<=2&&R>=2) ok=1; //2作为偶素数且符合条件 单独判断 50 while (L%4!=1||L==1) //将区间边界缩小到符合 %4==1 51 L++; 52 while (R%4!=1) 53 R--; 54 cout<<cnt(L,R)+ok; 55 return 0; 56 }