Same GCDs

Same GCDs

Created by LXC on Wed Apr 3 02:49:51 2024

https://codeforces.com/problemset/problem/1295/D

ranting: 1800

tag: math, number theory

problem


$$\sum_{x=0}^{m-1} [\ \gcd(a, m) = \gcd(a + x, m)\ ]$$

多组测试数据, $T \leq 50,\ 1 \leq a < m \leq 10^{10}$

solution

$g = gcd(a, m)$

$gcd(a+x,m) = g$
所以$g|a+x \Rightarrow g|x$,令$u = \frac{a}{g}, v = \frac{m}{g}$,只需要求$gcd(u+t,v)=1$的个数,其中$ 0 \le t < v$

由于$gcd(u+t,v) = gcd((u+t) \bmod v,v)$,而$0 \le (u+t) \bmod v < v$

只需要求$gcd(t,v)=1, 0\le t < v$的个数

等价与求1到v中与v互质的个数,就是欧拉函数$\phi(v)$

答案就是$\phi(\frac{m}{gcd(a, m)})$

求$\phi(n)$可以在$O(\sqrt n)$完成

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

#include <bits/stdc++.h>
// #define SINGLE_INPUT
#define ll long long
#define ull unsigned long long
#define N 500005
#define MOD 998244353
using namespace std;

template<class t,class u> ostream& operator<<(ostream& os,const pair<t,u>& p) {
return os<<'['<<p.first<<", "<<p.second<<']';
}
template<class t> ostream& operator<<(ostream& os,const vector<t>& v) {
os<<'['; int s = 1;
for(auto e:v) { if (s) s = 0; else os << ", "; os << e; }
return os<<']';
}
template<class t,class u> ostream& operator<<(ostream& os,const map<t,u>& mp){
os<<'{'; int s = 1;
for(auto [x,y]:mp) { if (s) s = 0; else os << ", "; os<<x<<": "<<y; }
return os<<'}';
}

ll phi(ll n) {
ll rt = n;
for (ll i=2; i*i<=n; i++) {
if (n%i) continue;
while (n%i == 0) n/=i;
rt /= i;
rt *= i-1;
}
if (n != 1) {
rt /= n;
rt *= n-1;
}
return rt;
}

void sol() {
ll a, m;
cin >> a >> m;
cout << phi(m/gcd(a, m)) << endl;
}

int main() {
cout << setprecision(15) << fixed;
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
#ifndef SINGLE_INPUT
int t;
cin >> t;
while (t--) {
sol();
}
#else
sol();
#endif
return 0;
}