常用于加密算法中,如仿射算法。
#include <stdio.h> #include <iostream> #include <algorithm> using namespace std; //返回d=gcd(a,b);和对应于等式ax+by=d中的x,y long long extend_gcd(long long a, long long b, long long &x, long long &y){ if(a == 0 && b == 0) return -1;//无最大公约数 if(b == 0){ x = 1; y = 0; return a; } long long d = extend_gcd(b, a % b, y, x); y -= a / b * x; return d; } //*********求逆元素******************* //ax = 1(mod n) long long mod_reverse(long long a, long long n){ long long x, y; long long d = extend_gcd(a, n, x, y); if(d == 1) return (x % n + n) % n; else return -1; } int main(){ long long n, m; while(~scanf("%d%d", &m, &n)){ printf("%lld\n", mod_reverse(m, n)); } return 0; }