1256 乘法逆元

基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题
 收藏
 关注
给出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,如果有多个满足条件的,输出最小的。
Input示例
2 3
Output示例
2
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>

typedef long long ll;
using namespace std;

ll ex_gcd(ll n,ll m,ll &x,ll &y){
	if(m == 0){
		x = 1;
		y = 0;
		return n;
	}
	int ans = ex_gcd(m,n%m,y,x);
	y -=  x*(n/m);
	return ans;
}
ll inv(ll n,ll m){
	ll x,y;
	ex_gcd(n,m,x,y);
	x = (x%m+m)%m;
	return x;
}
int main()
{
	ll n,m;
	scanf("%lld %lld",&n,&m);
	ll ans = inv(n,m);
	printf("%lld
",ans);
	return 0;
}


原文地址:https://www.cnblogs.com/Nlifea/p/11746033.html