题目链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1256

给出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

题解:扩展GCD
 #include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <iomanip>
#include <cmath>
#include <ctime>
#include <map>
#include <set>
#include <queue>
using namespace std;
#define lowbit(x) (x&(-x))
#define max(x,y) (x>y?x:y)
#define min(x,y) (x<y?x:y)
#define MAX 100000000000000000
#define MOD 1000000007
#define pi acos(-1.0)
#define ei exp(1)
#define PI 3.141592653589793238462
#define INF 0x3f3f3f3f3f
#define mem(a) (memset(a,0,sizeof(a)))
typedef long long ll;
ll gcd(ll a,ll b){
return b?gcd(b,a%b):a;
}
bool cmp(int x,int y)
{
return x>y;
}
const int N=;
const int mod=1e9+;
/*
* 扩展欧几里得法(求ax + by = gcd)
*/
// 返回d = gcd(a, b);和对应于等式ax + by = d中的x、y
ll extendGcd(ll a,ll b,ll &x,ll &y)
{
if (a == && b == ){
return -; // 无最大公约数
}
if (b == ){
x = ;
y = ;
return a;
}
ll d = extendGcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
// 求逆元 ax = 1(mod n)
ll modReverse(ll a, ll n)
{
ll x, y;
ll d = extendGcd(a, n, x, y);
if (d == ){
return (x % n + n) % n;
}
else{
return -; // 无逆元
}
}
int main()
{
ll M, N;
while (cin >> M >> N){
cout << modReverse(M, N) << endl;
}
return ;
}
04-24 21:36
查看更多