CF 1295D Same GCDs

4 篇文章 0 订阅

题目链接:https://codeforces.com/contest/1295/problem/D

You are given two integers a and m. Calculate the number of integers x such that 0≤x<m and gcd(a,m)=gcd(a+x,m).

Note: gcd(a,b) is the greatest common divisor of a and b.

Input
The first line contains the single integer T (1≤T≤50) — the number of test cases.

Next T lines contain test cases — one per line. Each line contains two integers a and m (1≤a<m≤1010).

Output
Print T integers — one per test case. For each test case print the number of appropriate x-s.

Example
input
3
4 9
5 10
42 9999999967
outpu
6
1
9999999966
Note
In the first test case appropriate x-s are [0,1,3,4,6,7].

In the second test case the only appropriate x is 0.

题意

给定数 a,m,求解 x 的个数。x 满足 x ∈ [0,m),gcd(a,m) = gcd(a+x,m)

思路

设a = xg,m = yg,则:
g c d ( x g , y g ) = g c d ( x g + z , y g ) = g gcd(xg,yg) = gcd(xg+z,yg) = g gcd(xg,yg)=gcd(xg+z,yg)=g
那么 z = kg,因为z∈[0,m),所以 k∈[0,y)

也就是 gcd(x+k,y) = 1
求解 k∈[x,x+y) 与 y 互质的数的个数

对于任意与 y 互质的数 p 和任意正整数 c
满足:

gcd(p+cy,y) = gcd((p+cy)%y,y) = gcd(p,y) = 1

显然 p+cy 与 y 互质

那么分成两个区间来看:
对于[x,y]区间内,答案是 k∈[x,y] 与 y 互质的个数
对于(y,x+y)区间内,答案是 k∈(0,y) 与 y 互质的个数
两个答案区间合并,就是 φ(y)

AC代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll maxn = 100010;
ll gcd(ll a,ll b)
{
    return b==0 ? a : gcd(b,a%b);
}
ll pri[maxn],tot;
bool v[maxn];
void primes()
{
    tot = 0;
    memset(v,true,sizeof(v));
    for(ll i=2;i<maxn;i++){
        if(v[i])
            pri[++tot] = i;
        for(ll j=1;j<=tot&&pri[j]*i<maxn;j++){
            v[i*pri[j]] = false;
            if(i%pri[j]==0) break;
        }
    }
}
ll phi(ll n)
{
    ll ans = n;
    for(ll i=1;pri[i]*pri[i] <=n;i++){
        if(n%pri[i]==0){
            ans = ans/pri[i]*(pri[i]-1);
            while(n%pri[i]==0)
                n /= pri[i];
        }
    }
    if(n>1) ans = ans/n*(n-1);
    return ans;
}
ll T,a,m,x,y;
int main()
{
    cin>>T;
    primes();
	while(T--){
		cin>>a>>m;
		ll g = gcd(a,m);
        x = a/g,y = m/g;
		ll ans = phi(y);
		cout<<ans<<endl;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逃夭丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值