解 ax + by = gcd(a,b);
gcd : { int gcd(int a, int b) { return b ? a : gcd(b, a%b); } }
ax+ by = 1 (gcd(a,b) = 1)
ax + by = 1 => bx + (a%b)y = 1 => bx + (a-(a/b)*b)y = 1 => ya + (x - (a/b)y)b = 1
逆元 : ax = 1(mod p) => ax - py = 1 同理.
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int a, p;
void exgcd(int a, int b, int &g, int &x, int &y) {
if(!b) { g = a; x = 1; y = 0; return ; }
exgcd(b, a%b, g, y, x); y -= a/b*x;
}
int main() {
freopen("exgcd.in", "r", stdin);
freopen("exgcd.out", "w", stdout);
scanf("%d%d\n", &a, &p);
int x, y, g;
exgcd(a, p, g, x, y);
x = (x < 0) ? x += p : x;
printf("%d\n", x);
fclose(stdin);
fclose(stdout);
return 0;
}