[NOIP2012] 同余方程|扩展欧几里得算法

题目描述

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

输入

输入文件为 mod.in。
输入只有一行,包含两个正整数 a, b,用一个空格隔开。

输出

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

样例输入

3 10

样例输出

7

提示

【数据范围】

对于 40%的数据,2 ≤b≤ 1,000;

对于 60%的数据,2 ≤b≤ 50,000,000;

对于 100%的数据,2 ≤a, b≤ 2,000,000,000。

 

扩展欧几里得算法,求ax+by=1时的一组解使x最小。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
using namespace std;
void ex_gcd(int a,int b,int &x,int &y)
{
    if (b==0) { x=1; y=0; return; }
    ex_gcd(b,a%b,x,y);
    int t=x; x=y; y=t-a/b*x;
}
int main()
{
    int x,y,a,b;
    scanf("%d%d",&a,&b);
    ex_gcd(a,b,x,y);
    if (x<0) x+=b;
    printf("%d",x%b);
    return 0;
}
原文地址:https://www.cnblogs.com/ws-fqk/p/4694497.html