Modular Inverse ZOJ - 3609 (Extended Euclidean Inverse Element)

Modular Inverse

Topic link: ZOJ - 3609

Given the modulus m, find the inverse x of a, which is equivalent to solving ax≡1(modm); it can be converted into the equation ax-my=1; at this time, it can be obtained by extended Euclidean r=gcd(a, m);
if r!=1, there is no x that is the inverse of a;
if r==1, the x obtained by extended Euclid is the inverse x of a, at this time Then adjust x to the range of 0~m-1; then find the inverse of 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=ta/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;
}


Guess you like

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