標籤:style blog color 使用 strong os
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型,可以存0111 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==151 L++;52 while (R%4!=1)53 R--;54 cout<<cnt(L,R)+ok;55 return 0;56 }