您的位置:首页 > 移动开发

poj 2773 Happy 2006(容斥原理+二分)

2014-05-11 22:47 369 查看
Happy 2006
Time Limit: 3000MSMemory Limit: 65536K
Total Submissions: 9139Accepted: 3079
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
2006 1
2006 2
2006 3
Sample Output
1
3
5
#include <iostream>#include <cstdio>#include <vector>using namespace std;#define ll long longll m , K;vector<int> p;void initial(){p.clear();for(int i = 2; i*i <= m; i++){if(m%i==0){p.push_back(i);while(m%i==0) m /= i;}}if(m > 1) p.push_back(m);}ll Inclusion_Exclusion(ll x){int cnt = p.size();ll ans = 0;for(int i = 1; i < (1<<cnt); i++){ll ret = 1 , sum = 0;for(int j = 0; j < cnt; j++){if(i&(1<<j)){sum++;ret *= p[j];}}if(sum%2==0) ans -= x/ret;else ans += x/ret;}return x-ans;}void computing(){ll l = 0 , r = ((ll)1)<<62;while(l < r){ll mid = (l+r)/2;if(Inclusion_Exclusion(mid) >= K) r = mid;else l = mid+1;}printf("%lld\n" , l);}int main(){while(cin >> m >> K){initial();computing();}return 0;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: