CF1295D Same GCDs

Same GCDs

link

Solution

\[ gcd(a,m)=gcd(a+x,m)\ \ (0<=x<m) $$等价于$$ gcd(a,m)=\left\{\begin{matrix} gcd(a+x-m,m)& ,a+x\geq m\\ gcd(a+x,m)& ,a+x< m \end{matrix}\right. $$等价于$$ gcd(a,m) =gcd(x',m) \ \ (0<=x'<m)\]

若设\(gcd(a,m)=g\),则 \(gcd(x'/g,m/g)=1\),又易得 \(0<=x'/g<m/g且可以取遍\),因此,所求x'的个数即为$$\phi(m/g)$$

Code

#include<bits/stdc++.h>
#define LL long long
using namespace std;
LL t,a,m;

LL phi(LL x)
{
	LL ret=x;
	for(LL i=2;i<=sqrt(x);i++)
		if(x%i==0)
		{
			ret=ret/i*(i-1);
			while(x%i==0)x/=i;
		}
	if(x>1)ret=ret/x*(x-1);
	return ret;
}

int main()
{
	scanf("%lld",&t);
	while(t--)
	{
		scanf("%lld%lld",&a,&m);
		LL g=__gcd(a,m);
		LL ans=phi(m/g);
		printf("%lld\n",ans);
	}
}
posted @ 2020-02-23 11:15  liqgnonqfu  阅读(98)  评论(0编辑  收藏  举报