原题:
D. Same GCDs
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given two integers a and m. Calculate the number of integers x such that 0≤x
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
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
Output
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的个数,使得gcd(a,m)=gcd(a+x,m). 其中gcd为最大公约数。
程序:
#include
using namespace std;
const int maxn = 1e5 +5;
typedef long long ll;
ll phi(ll n)
{
double result = n;
for (ll p = 2; p * p <= n; ++p) {
if (n % p == 0) {
while (n % p == 0)
n /= p;
result *= (1.0 - (1.0 / (double)p));
}
}
if (n > 1) result *= (1.0 - (1.0 / (double)n));
return (ll)result;
}
ll t,a,m;
int main()
{
ios::sync_with_stdio(false);
cin>>t;
while(t--)
{
cin>>a>>m;
cout<<phi(m/__gcd(a,m))<<endl;
}
return 0;
}
解答:
设
现在由最大公约数的定理可知 g c d ( a , b ) = g c d ( b , a % b ) gcd(a,b) = gcd(b,a \%b ) gcd(a,b)=gcd(b,a%b)
所以 g c d ( a + x , m ) = g c d ( m , ( a + x ) % m ) gcd(a+ x ,m) = gcd(m,(a+x)\%m ) gcd(a+x,m)=gcd(m,(a+x)%m)
所以要找 g c d ( m , ( a + x ) % m ) = d gcd(m,(a+x)\%m) = d gcd(m,(a+x)%m)=d的x个数,且要求 x ∈ [ 0 , m ) x ∈ [0,m) x∈[0,m)
将因子d除掉,即 g c d ( ( a + x ) % m d , m d ) = 1 gcd(\frac{(a + x)\%m}{d},\frac{m}{d}) = 1 gcd(d(a+x)%m,dm)=1
因此,最后结果等价于寻找 m d \frac{m}{d} dm的非因子的个数,直接欧拉函数就完事