当前位置: 代码迷 >> 综合 >> Happy 2006(欧拉函数+互质)
  详细解决方案

Happy 2006(欧拉函数+互质)

热度:19   发布时间:2023-12-05 02:29:32.0

题目: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.

大意:给定一个数m,求第k位与它互质的数.

思路:将m之前的数求出来存入数组记录,那么假如k>m呢?容易证得,对于一个小于m的数,如果gcd(a,m)=1,那么gcd(a+m,m)=1,所以,我们只需要求出m之前有num个与m互质的数,那么k/num*m+m之前与其互质的第k%num个数,即rec[k%num]+k/num*m。我以为这就完了,没想到wa了,然后我发现当k%num=0时的数据错了,所以当k%num=0时,答案应该为rec[k%num]+(k-1)/num*m。然后一交,tle了。。。。。然后de半天bug发现long long的问题,开成int就可以ac。(涨知识了,long long也会卡时间。。。)

代码

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
#define ll int
ll rec[1000005];
ll gcd(ll a,ll b){return b==0?a:gcd(b,a%b);
}
int main()
{ll m,k;while(scanf("%d %d",&m,&k)!=EOF){ll num=0;memset(rec,0,sizeof(rec));for(ll i=1;i<=m;i++){if(gcd(i,m)==1) rec[++num]=i;}if(k%num==0) printf("%d\n",rec[num]+(k-1)/num*m);else printf("%d\n",rec[k%num]+k/num*m);}
}

  相关解决方案