Modular Inverse ZOJ - 3609 (Extended Euclidean Algorithm)

The remainder of ax to m is equal to 1 to the remainder of m -> ax + my = 1 = gcd(a,m)

Just use the extended Euclidean algorithm. When gcd(a,m) is not equal to 1, there is no answer


#include <iostream>

using namespace std;
typedef long long ll;

void ex_gcd(ll a,ll b,ll &x,ll &y,ll &d){
	if(!b){
		d = a;x = 1;y = 0;
	}
	else{
		ex_gcd(b,a % b,y,x,d);
		y -= x * (a / b);
	}
}

int main(void){
	int t;
	cin >> t;
	while(t--){
		ll a,m;
		ll d,x,y;
		cin >> a >> m;
		ex_gcd(a,m,x,y,d);
		if(d == 1){
			while(x <= 0){
				x += m;
			}
			cout << x << endl;
		}
		else{
			cout << "Not Exist" << endl;
		}
	}
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324674047&siteId=291194637