CodeForces - 1295D Same GCDs(欧拉函数)

题目链接:点击查看

题目大意:给出两个正整数 a 和 m ,再给出 x 的范围为[ 0 , m ),现在要求满足 gcd ( a , m ) = gcd ( a + x , m ) 时 x 的个数

题目分析:因为辗转相除法的定义:gcd(a,b) = gcd(b,a mod b)可知,当 i ∈ [ a , m ] 和 i ∈ [ m , 2 * m ] 时,gcd( i ,m ) 相等的 i 的个数相同,因为每次都是对第二个数取模,所以具有周期性,而题目要求我们求得是 i ∈ [ a , m + a -1 ] 时的个数,因为长度为一个完整的周期,所以我们不妨将其问题转换为 i ∈ [ 0 , m ] 时,满足gcd( i , m ) = = gcd ( a , m ) 的个数

剩下的就能用欧拉函数解决了:

\sum_{i=1}^{n}[gdc(i,n)=d]=\sum_{i=1}^{n}[gdc(\frac{i}{d},\frac{n}{d})=1]=\phi (\frac{n}{d})

也就是求m / gcd ( a , m ) 的欧拉函数

代码:

#include<iostream>
#include<cstdio> 
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<sstream>
using namespace std;
 
typedef long long LL;
 
const int inf=0x3f3f3f3f;

const int N=1e5+100;

LL eular(LL n)
{
    LL ans=n;
    for(LL i=2;i*i<=n;i++)
    {
        if(n%i==0)
        {
            ans=ans/i*(i-1);
            while(n%i==0)
                n/=i;
        }
    }
    if(n>1) 
		ans=ans/n*(n-1);
    return ans;
}

int main()
{
//	freopen("input.txt","r",stdin);
//	ios::sync_with_stdio(false);
	int w;
	cin>>w;
	while(w--)
	{
		LL a,m;
		scanf("%lld%lld",&a,&m);
		m/=__gcd(a,m);
		printf("%lld\n",eular(m));
	}
 
 
 
 
 
	
	
	
	
	
	
	
	
	
	return 0;
}
发布了577 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_45458915/article/details/104114132