最大公约数、欧几里得算法、拓展欧几里得算法、同余方程

最大公约数(Greatest Common Divisors)。

欧几里得算法

int gcd(int a, int b) {
	return b == 0 ? a : gcd(b, a % b);
}

拓展欧几里得算法

int exgcd(int a, int b, int &x, int &y) {
    if (!b) { x = 1; y = 0; return a; }
    int result = exgcd(b, a % b, x, y);
    int temp = x; x = y; y = temp - a / b * y;
    return result;
}

同余方程

应用拓展欧几里得算法。如洛谷P1082:

/* Luogu 1082 同余方程
 * Au: GG
 * ax ≡ 1 (mod b)
 * ax + by = 1
 */
#include <bits/stdc++.h>
using namespace std;

int exgcd(int a, int b, int &x, int &y) {
    if (!b) { x = 1; y = 0; return a; }
    int result = exgcd(b, a % b, x, y);
    int temp = x; x = y; y = temp - a / b * y;
    return result;
}

int main() {
    int a, b, x, y;
    scanf("%d%d", &a, &b);
    exgcd(a, b, x, y);
    printf("%d
", (x + b) % b);
    return 0;
}

Post author 作者: Grey
Copyright Notice 版权说明: Except where otherwise noted, all content of this blog is licensed under a CC BY-NC-SA 4.0 International license. 除非另有说明,本博客上的所有文章均受 知识共享署名 - 非商业性使用 - 相同方式共享 4.0 国际许可协议 保护。
原文地址:https://www.cnblogs.com/greyqz/p/7290737.html