C - 乘法逆元

给出2个数M和N(M < N),且M与N互质,找出一个数K满足0 < K < N且K * M % N = 1,如果有多个满足条件的,输出最小的。

Input

输入2个数M, N中间用空格分隔(1 <= M < N <= 10^9)

Output

输出一个数K,满足0 < K < N且K * M % N = 1,如果有多个满足条件的,输出最小的。

Sample Input

2 3

Sample Output

2
k就是m的逆元
#include<stdio.h>
#include <iostream>
using namespace std;
typedef long long ll;
ll exgcd(ll a,ll b,ll &x,ll &y)
{
	if (b==0)
	{
		x = 1;
		y = 0;
		return a;
	}
	ll r = exgcd (b,a%b,y,x);
	y -= a / b * x;
	
	return r; //最大公约数
}
ll inv(ll a,ll n) //求逆元 
{
    ll x, y;
    ll g = exgcd(a, n, x, y);
    if (g==1)
    	return ((x % n) + n) % n;
    else
    	return -1;
}
int main()
{
	ll m,n;
	scanf("%lld %lld",&m,&n);
	printf("%lld\n",inv(m,n));
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40912854/article/details/81188338