The modular modular multiplicative inverse of an integer a modulo m is an integer x such that a-1≡x (mod m). This is equivalent to ax≡1 (mod m).
Input
There are multiple test cases. The first line of input is an integer T ≈ 2000 indicating the number of test cases.
Each test case contains two integers 0 < a ≤ 1000 and 0 < m ≤ 1000.
Output
For each test case, output the smallest positive x. If such x doesn’t exist, output “Not Exist”.
Sample Input
3
3 11
4 12
5 13
Sample Output
4
Not Exist
8
References
题意,求一个最小的正数使得ax %m == 1
我们可以将这个式子展开即(ax-1) % m = 0 ,即ax-1 = y*m,将其移动到右边即是ax - my = 1,显然我们要用到扩展欧几里得,详细解释在代码注释里面
代码如下:
#include
#include
#include
using namespace std;
int t,a,m;
typedef long long ll;
ll extgcd(ll a,ll b,ll &x,ll &y){//我表示没有看懂,展示当模板强行记住,我好笨啊。
ll d = a;
if(b != 0){
d = extgcd(b,a%b,y,x);
y -= (a/b)*x;
}else{
x = 1;
y = 0;
}
return d;
}
int main(void)
{
ll t;
cin >> t;
while(t--){
cin >> a >> m;
ll x,y;
ll ans = extgcd(a,m,x,y);
if(ans != 1)
cout << "Not Exist" << endl;
else{
/*因为拓展欧几里得是求ax+by=1的解,这里是ax-by=1,但当求的y为负数时 也可默认为前着转化为了后者
例如,我们得到一组解x0,y0那么a(x0+b)+b(y0-a)与原式相等,当x为正时,则y一定为负.*/
while(x <= 0)
x += m;
cout << x << endl;
}
}
return 0;
}