poj 2773 Happy 2006(求第k个与n互质的数)
2013-12-04 09:02
323 查看
Happy 2006
DescriptionTwo positive integers are said to be relatively prime to each other if the Great Common Divisor (GCD) is 1. For instance, 1, 3, 5, 7, 9...are all relatively prime to 2006.Now your job is easy: for the given integer m, find the K-th element which is relatively prime to m when these elements are sorted in ascending order.InputThe input contains multiple test cases. For each test case, it contains two integers m (1 <= m <= 1000000), K (1 <= K <= 100000000).OutputOutput the K-th element in a single line.Sample Input
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 8779 | Accepted: 2913 |
2006 1 2006 2 2006 3Sample Output
1 3 5
题意:给出m、k,求k个与m互质的数。
思路:我们知道gcd(b×t+a,b)=gcd(a,b) (t为任意整数),如果a与b互素,则b×t+a与b也一定互素,如果a与b不互素,则b×t+a与b也一定不互素。故与m互素的数对m取模具有周期性,则根据这个方法我们就可以很快的求出第k个与m互素的数。
AC代码:
#include <iostream>#include <cmath>#include <cstdlib>#include <cstring>#include <cstdio>#include <queue>#include <ctime>#define ll __int64using namespace std;const int maxn = 1000000;int prime[maxn + 5];bool vis[maxn + 5], flag[maxn + 5];int cnt;void getprime(){memset(vis, false, sizeof(vis));cnt = 0;for(int i = 2; i <= maxn; i++)if(!vis[i]){prime[cnt++] = i;for(int j = 1; j * i<= maxn; j++)vis[j * i] = true;}}int euler(int n){memset(flag, false, sizeof(flag));int ret = n, m = n;for(int i = 0; prime[i] * prime[i] <= n; i++)if(n % prime[i] == 0){ret = ret / prime[i] * (prime[i] - 1);while(n % prime[i] == 0) n /= prime[i];for(int j = prime[i]; j <= m; j += prime[i])flag[j] = true;}if(n > 1){ret = ret / n * (n - 1);for(int j = n; j <= m; j += n)flag[j] = true;}return ret;}int find(int n, int id){int cnt = 0;for(int i = 1; i <= n; i++){if(!flag[i]) cnt++;if(cnt == id) return i;}return -1;}int main(){int m, k;getprime();while(cin>>m>>k){if(m == 1){cout<<k<<endl;continue;}int len = euler(m);cout<<((k - 1)/ len) * m + find(m, (k - 1) % len + 1)<<endl;}return 0;}
相关文章推荐
- (Relax 1.15)POJ 2773 Happy 2006(欧拉函数的应用:求与n互质的第k个数)
- POJ 2773 Happy 2006(求第k个与m互素的数)
- POJ 2773 Happy 2006(求第k个和m互素的数/欧拉函数)
- poj 2773 Happy 2006
- POJ 2773 Happy 2006
- POJ 2773 Happy 2006 (二分+容斥)
- POJ 2773 - Happy 2006(素数判定 欧几里得算法)
- poj 2773 Happy 2006
- POJ 2773 Happy 2006 解题报告(容斥原理+质因数分解)
- POJ2773 Happy 2006【容斥原理】
- POJ 2773 Happy 2006
- poj2773 Happy 2006(二分+容斥)
- POJ 2773 Happy 2006(容斥原理)
- POJ 2773:Happy 2006
- poj 2773 Happy 2006
- POJ 2773 Happy 2006 (分解质因数+容斥+二分 或 欧几里德算法应用)
- POJ_2773_Happy 2006_ 欧几里得算法
- poj 2773 Happy 2006 容斥原理+筛素数+二分
- poj2773 Happy 2006
- POJ 2773 Happy 2006