Time Limit: 3000MS | Memory Limit: 65536KB | 64bit IO Format: %I64d & %I64u |
Description
Two 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.
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.
Input
The input contains multiple test cases. For each test case, it contains two integers m (1 <= m <= 1000000), K (1 <= K <= 100000000).
Output
Output the K-th element in a single line.
Sample Input
2006 1 2006 2 2006 3
Sample Output
1 3 5
解决方案:题意是求第k个与m互质的数是哪个数。假设m的质因数为p1,p2,p3.
那么若s与m互质,它将是第s-s/p1-s/p2-s/p3+s/(p1*p2)+s/(p1*p3)+s/(p2*p3)-s/(p1*p2*p3)个数。所以,可以通过二分查找来确定这个数。
code:
#include<iostream>
#include<cstdio>
#include<vector>
#include<cstring>
#define MMAX 1000000
using namespace std;
bool vis[MMAX];
vector <int > p,f;
void init()
{
p.clear();
memset(vis,true,sizeof(vis));
p.push_back(2);
for(int i=3; i<MMAX; i+=2)
{
if(vis[i])
{
p.push_back(i);
for(int j=i+i; j<MMAX; j+=i)
vis[j]=false;
}
}
}///素数打表
void prime()
{
p.clear();
memset(vis, true, sizeof(vis));
p.push_back(2);
for (int i=3; i<MMAX; i+=2)
if (vis[i])
{
p.push_back(i);
for (int j=i+i; j<MMAX; j+=i) vis[j] = false;
}
}
long long ok(long long mid)
{
long long c,v,kk,all=mid;
for(int i=1; i<(1<<f.size()); i++)
{
c=0,v=1;
for(int j=0; j<f.size(); j++)
{
if((1<<j)&i)
{
c++,v*=f[j];
}
}
kk=mid/v;
if(c%2==1) all-=kk;
else all+=kk;
}
return all;
}
int main()
{
long long m,k;
//prime();
init();
//cout<<p[0];
while(~scanf("%lld%lld",&m,&k))
{
f.clear();
for(unsigned i=0; i<p.size()&&p[i]<=m; i++)
{
if(m%p[i]==0)
{
f.push_back(p[i]);
while(m%p[i]==0) m/=p[i];
}
}
long long low=1,high=1e17,mid;
while(low<high)
{
mid=(low+high)/2;
if(ok(mid)>=k) high=mid;
else low=mid+1;
}
cout<<low<<endl;
}
return 0;
}