最近改自己的错误代码改到要上天,心累。
这是迄今为止写的最心累的博客。
| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 18707 | Accepted: 4998 |
Description
Your program is given 2 numbers: L and U (1<=L< U<=2,147,483,647), and you are to find the two adjacent primes C1 and C2 (L<=C1< C2<=U) that are closest (i.e. C2-C1 is the minimum). If there are other pairs that are the same distance apart, use the first pair. You are also to find the two adjacent primes D1 and D2 (L<=D1< D2<=U) where D1 and D2 are as distant from each other as possible (again choosing the first pair if there is a tie).
Input
Output
Sample Input
2 17
14 17
Sample Output
2,3 are closest, 7,11 are most distant.
There are no adjacent primes.
题意就是找给定的区间内距离最近的两个素数和距离最远的两个素数。
因为给的数很大,不能从(1-U)筛素数,这样写会re,我是智障,我一开始从1到U开始筛的素数,被T飞了,
想着自己好不容易改了个筛选法求欧拉函数的代码(改的这个代码,传送门:http://www.cnblogs.com/ZERO-/p/6582239.html)写这道题,就一直坚持不懈的改。
样例可以过啊,交上就不可以。后来越改越不靠谱,Memory Limit Exceeded,Runtime Error。。。
这才反应过来是自己的代码写的有问题,要换思路。因为给的数很大,所以从头开始筛素数是不可以的,空间上不允许,所以才MLE。。。
然后就看了一下区间筛素数,把人家求区间有几个素数的代码拿来改(传送门:http://www.cnblogs.com/nowandforever/p/4515612.html),改的我头大,但好在最后a了,唉,心累啊。
人家的题目代码:
给定整数a和b,请问区间[a,b)内有多少个素数?
a<b<=10^12
b-a<=10^6
因为b以内合数的最小质因数一定不超过sqrt(b),如果有sqrt(b)以内的素数表的话,就可以把筛选法用在[a,b)上了,先分别做好[2,sqrt(b))的表和[a,b)的表,然后从[2,sqrt(b))的表中筛得素数的同时,也将其倍数从[a,b)的表中划去,最后剩下的就是区间[a,b)内的素数了。
有的时候需要求出某个特定区间的素数,但是数可能很大,数组也开不小,所以需要进行下标偏移,这样才可以使用筛选法。
区间素数统计代码:
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 typedef long long ll; 6 const int maxn=1e6+10; 7 bool is_prime[maxn]; 8 bool is_prime_small[maxn]; 9 ll prime[maxn]; 10 ll prime_num=0; 11 void segment_sieve(ll a,ll b){ 12 for(ll i=0;i*i<b;++i) is_prime_small[i]=true; 13 for(ll i=0;i<b-a;++i) is_prime[i]=true; 14 for(ll i=2;i*i<b;++i){ 15 if(is_prime_small[i]){ 16 for(ll j=2*i;j*j<b;j+=i) is_prime_small[j]=false; 17 for(ll j=max(2LL,(a+i-1)/i)*i;j<b;j+=i) is_prime[j-a]=false; 18 } 19 } 20 for(ll i=0;i<b-a;++i) 21 if(is_prime[i]) prime[prime_num++]=i+a; 22 } 23 int main(){ 24 ll a,b; 25 while(~scanf("%lld%lld",&a,&b)){ 26 prime_num=0; 27 memset(prime,0,sizeof(prime)); 28 segment_sieve(a,b); 29 printf("%lld\n",prime_num); 30 } 31 return 0; 32 }