codevs 1200 同余方程 逆元

时间:2021-08-06 10:07:20
题目描述 Description

求关于 x 同余方程 ax ≡ 1 (mod b)的最小正整数解。

输入描述 Input Description

输入只有一行,包含两个正整数 a, b,用 一个 空格隔开。

输出描述 Output Description

输出只有一行包含一个正整数x0,即最小正整数解,输入数据保证一定有解。

样例输入 Sample Input

3 10

样例输出 Sample Output

7

数据范围及提示 Data Size & Hint

【数据范围】
对于 40%  的数据, 2 ≤b≤ 1,000 ;
对于 60% 的数据, 2 ≤b≤ 50,000,000 
对于 100%  的数据, 2 ≤a, b≤ 2,000,000,000

题意:求逆元

思路:因为b可能不是素数,所以利用扩展欧几里德求解

#include<iostream>
#include<cstdio>
#include<cmath>
#include<string>
#include<queue>
#include<algorithm>
#include<stack>
#include<cstring>
#include<vector>
#include<list>
#include<set>
#include<map>
using namespace std;
#define ll long long
//#define mod 1000000007
int scan()
{
int res = 0 , ch ;
while( !( ( ch = getchar() ) >= '0' && ch <= '9' ) )
{
if( ch == EOF ) return 1 << 30 ;
}
res = ch - '0' ;
while( ( ch = getchar() ) >= '0' && ch <= '9' )
res = res * 10 + ( ch - '0' ) ;
return res ;
}
char a[1010];
ll flag[30];
ll mod;
void extend_Euclid(ll a, ll b, ll &x, ll &y)
{
if(b == 0)
{
x = 1;
y = 0;
return;
}
extend_Euclid(b, a % b, x, y);
ll tmp = x;
x = y;
y = tmp - (a / b) * y;
}
int main()
{
ll x,y,a,m;
cin>>a>>m;
extend_Euclid(a,m,x,y);
cout<<(x%m+m)%m<<endl;
return 0;
}