1. 程式人生 > >擴充套件歐幾里得求乘法逆元

擴充套件歐幾里得求乘法逆元

對於正整數a和m如果滿足公式,那麼x的最小正整數解稱為a模m的逆元。

可以證明等價於 gcd(a,m)=1即a*x+m*y=1,因此如果gcd(a,m)!=1就一定是無解的。

現在就可以用擴充套件歐幾里得求x的通解了即x=x0+(m/1)t,x0%m為最小正整數解。

如果m為負數,可以先取絕對值,那麼如果x0%m為負數,只要再加上abs(m)就是答案了。

例題:

Modular Inverse
Time Limit: 2 Seconds      Memory Limit: 65536 KB

The modular modular multiplicative inverse of an integer a

 modulo m is an integer x such that a-1x (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

求乘法逆元裸題。

#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
int e_gcd(int a, int b, int &x, int &y)
{
	if (b == 0)
	{
		x = 1;
		y = 0;
		return a;
	}
	int ans = e_gcd(b, a%b, x, y);
	int temp = x;
	x = y;
	y = temp - (a / b)*y;
	return ans;
}
int cal(int a, int m)
{
	int x, y, ans;
	int gcd = e_gcd(a, m, x, y);
	if (gcd != 1) return -1;
	m = abs(m);
	ans = x % m; 
	if (ans <= 0) ans += m;
	return ans;
}
int main()
{
	int ans, t, a, m;
	scanf("%d", &t);
	while (t--)
	{
		scanf("%d%d", &a, &m);
		ans = cal(a, m);
		if (ans == -1) printf("Not Exist\n");
		else printf("%d\n", ans);
	}
	return 0;
}