扩展欧几里得例题(luogu_1082)

luo gu

由$a*x \equiv1 (\mod b)$ 推导为扩展欧几里得

  • ->$a*x \mod b == 1 \mod b$
  • ->$a*x \mod b =1$
  • 即-> $ax = nb+1$(n是常数)
  • -> $ax-nb=1$
  • ->$ax+yb=1$ (y = -n,常数无影响)
    模板:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    #include <iostream>
    #include <string.h>
    #include <queue>

    using namespace std;

    int exgcd(int a,int b,long long & x,long long & y) {
    if (b == 0) {
    x = 1;
    y = 0;
    return a;
    }
    int res = exgcd(b,a%b,x,y);
    // 回溯的时候进行 推倒x,y
    long long temp = y;
    y = x - (a/b)*y;
    x = temp;
    return res;
    }


    int main() {
    int a,b;
    long long x,y;
    cin >> a >> b;
    exgcd(a,b,x,y);
    if (x > 0) {
    while (x > 0)
    x -= abs(b);
    x += abs(b);
    cout << x << endl;
    }
    else {
    while (x < 0)
    x += abs(b);
    cout << x << endl;
    }
    return 0;
    }

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!