Modular Inverse
题目链接: ZOJ - 3609给定模数m, 求a的逆元x, 相当于求解ax≡1(modm);可以转化成方程ax-my=1;此时可以用扩展欧几里得求得r=gcd(a, m);
若r!=1则不存在x是a的逆元;
若r==1, 扩展欧几里得所求出的x即为a的逆元x, 此时再将x调整到0~m-1范围;就求得a的逆元;
#include <iostream> #include <algorithm> #include <string.h> #include <stdio.h> using namespace std; int exgcd(int a, int b, int &x, int &y){ if(b==0){ x=1; y=0; return a; } int r=exgcd(b, a%b, x, y); int t=x; x=y; y=t-a/b*y; return r; } int main(){ int T; cin >> T; while(T--){ int a, m, x, y; cin >>a >> m; int r = exgcd(a, m, x, y); if(r!=1) cout << "Not Exist\n"; else{ while(x<=0){ x+=m; } cout << x << endl; } } return 0; }