[Educational Codeforces Round 81 (Rated for Div. 2)] D. Same GCDs (数论,因子分解,容斥定理)
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 aa and mm. Calculate the number of integers xx such that 0≤x
Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.
Input
The first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.
Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a
Output
Print TT integers — one per test case. For each test case print the number of appropriate xx-s.
Example
input
Copy
3
4 9
5 10
42 9999999967
output
Copy
6
1
9999999966
Note
In the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].
In the second test case the only appropriate xx is 00.
题意:
T组数据,
每一组数据给定两个整数a和m
问有多少个x满足:
\(0 \le x < m\) 和\(\gcd(a, m) = \gcd(a + x, m)\)
思路:
设\(b=\gcd(a,m)\),那么问题等同于问:
区间\([a,a+m-1]\) 中有多少个数x使\(\gcd(x,m)=b\)
又因为\(\gcd(x/b,m/b)=1\) , 所以问题可以转化为 :
区间\([a/b,(a+m-1)/b]\) 中有多少个数x使\(\gcd(x,m/b)=1\)
即区间\([a/b,(a+m-1)/b]\)中有多少个数x与m/b互质。
我们知道这是一个因子分解+容斥定理的经典问题。
代码:
#include
#include
#include
#include
#include
#include
#include
#include