[NOIp 2012]同余方程

Description

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

Input

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

Output

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

Sample Input

3 10

Sample Output

7

Hint

【数据范围】

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

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

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

题解

既然保证有解,那么肯定有$gcd(a, b) = 1$,用$exgcd$求出$ax+by = 1$的一组解,再求出$x$的最小正整数解。

 1 //It is made by Awson on 2017.10.7
 2 #include <map>
 3 #include <set>
 4 #include <cmath>
 5 #include <ctime>
 6 #include <queue>
 7 #include <stack>
 8 #include <vector>
 9 #include <cstdio>
10 #include <string>
11 #include <cstdlib>
12 #include <cstring>
13 #include <iostream>
14 #include <algorithm>
15 #define LL long long
16 #define Max(a, b) ((a) > (b) ? (a) : (b))
17 #define Min(a, b) ((a) < (b) ? (a) : (b))
18 using namespace std;
19 
20 LL a, b, x, y;
21 
22 LL exgcd(LL a, LL b, LL &x, LL &y) {
23   if (b == 0) {
24     x = 1; y = 0;
25     return a;
26   }
27   LL c = exgcd(b, a%b, x, y);
28   LL t = x;
29   x = y;
30   y = t-a/b*y;
31   return c;
32 }
33 void work() {
34   scanf("%lld%lld", &a, &b);
35   LL gcd = exgcd(a, b, x, y);
36   printf("%lld
", (x%b+b)%b);
37 }
38 int main() {
39   work();
40   return 0;
41 }
原文地址:https://www.cnblogs.com/NaVi-Awson/p/7634959.html