题目链接:http://codeforces.com/contest/937
The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape.
The pine's trunk includes several branches, located one above another and numbered from 2 to y. Some of them (more precise, from 2 to p) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppers are known for their awesome jumping skills: the grasshopper at branch x can jump to branches .
Keeping this in mind, you wisely decided to choose such a branch that none of the grasshoppers could interrupt you. At the same time you wanna settle as high as possible since the view from up there is simply breathtaking.
In other words, your goal is to find the highest branch that cannot be reached by any of the grasshoppers or report that it's impossible.
The only line contains two integers p and y (2 ≤ p ≤ y ≤ 109).
Output the number of the highest suitable branch. If there are none, print -1 instead.
3 6
5
3 4
-1
In the first sample case grasshopper from branch 2 reaches branches 2, 4 and 6 while branch 3 is initially settled by another grasshopper. Therefore the answer is 5.
It immediately follows that there are no valid branches in second sample case.
题解:
问:在[2,y]范围内,不能被[2,p]整除的最大整数,其中p<=y, y<=1e9。
1.可知,小于y且大于p的最大素数即为答案,而两个素数间的间隔不会太大(好像是300左右),所以可以直接从y递减枚举答案ans,看是否不能被[2,p]整除。
2.由于p的范围也可达到1e9,如果直接判断ans能否被[2,p]整除,也必定会超时,所以需要优化。根据以往的经验,求一个数的因子ai,我们只需要枚举到sqrt(n),而与之对应的另一个因子aj为n/ai。那么对于此题,我们也可以这样优化:判断ans能否被[2,min(p,sqrt(y))]中的整除。这样整体复杂度就达到 300*sqrt(1e9)了。
代码如下:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <cstdlib> 6 #include <string> 7 #include <vector> 8 #include <map> 9 #include <set> 10 #include <queue> 11 #include <sstream> 12 #include <algorithm> 13 using namespace std; 14 typedef long long LL; 15 const double eps = 1e-8; 16 const int INF = 2e9; 17 const LL LNF = 9e18; 18 const int MOD = 1e9+7; 19 const int MAXN = 2e5+10; 20 21 int a[MAXN]; 22 int main() 23 { 24 int y, p; 25 while(scanf("%d%d",&p,&y)!=EOF) 26 { 27 bool flag = 0; 28 int ans = 0; 29 for(; y>p; y--) 30 { 31 bool f = true; 32 int m = sqrt(y); m++; 33 int maxx = min(m,p); 34 for(int i = 2; i<=maxx; i++) 35 if(y%i==0) 36 { 37 f = false; 38 break; 39 } 40 41 if(f) 42 { 43 printf("%d ", y); 44 flag = true; 45 break; 46 } 47 } 48 49 if(!flag) puts("-1"); 50 } 51 }