计算模乘逆元原理上有四种方法:
1.暴力算法
2.扩展欧几里得算法
3.费尔马小定理
4.欧拉定理
模乘逆元定义:满足 ab≡1(mod m),称b为a模乘逆元。以下是有关概念以及四种方法及程序。
文章出处:Modular Multiplicative Inverse
The modular multiplicative inverse of an integer a modulo m is an integer x such that
That is, it is the multiplicative inverse in the ring of integers modulo m. This is equivalent to
1. Brute Force
We can calculate the inverse using a brute force approach where we multiply a with all possible valuesx and find ax such that Here’s a sample C++ code:
int modInverse(int a, int m) { a %= m; for(int x = 1; x < m; x++) { if((a*x) % m == 1) return x; } }
Iterative Method
/* This function return the gcd of a and b followed by the pair x and y of equation ax + by = gcd(a,b)*/ pair<int, pair<int, int> > extendedEuclid(int a, int b) { int x = 1, y = 0; int xLast = 0, yLast = 1; int q, r, m, n; while(a != 0) { q = b / a; r = b % a; m = xLast - q * x; n = yLast - q * y; xLast = x, yLast = y; x = m, y = n; b = a, a = r; } return make_pair(b, make_pair(xLast, yLast)); } int modInverse(int a, int m) { return (extendedEuclid(a,m).second.first + m) % m; }
/* This function return the gcd of a and b followed by the pair x and y of equation ax + by = gcd(a,b)*/ pair<int, pair<int, int> > extendedEuclid(int a, int b) { if(a == 0) return make_pair(b, make_pair(0, 1)); pair<int, pair<int, int> > p; p = extendedEuclid(b % a, a); return make_pair(p.first, make_pair(p.second.second - p.second.first*(b/a), p.second.first)); } int modInverse(int a, int m) { return (extendedEuclid(a,m).second.first + m) % m; }
/* This function calculates (a^b)%MOD */ int pow(int a, int b, int MOD) { int x = 1, y = a; while(b > 0) { if(b%2 == 1) { x=(x*y); if(x>MOD) x%=MOD; } y = (y*y); if(y>MOD) y%=MOD; b /= 2; } return x; } int modInverse(int a, int m) { return pow(a,m-2,m); }
vector<int> inverseArray(int n, int m) { vector<int> modInverse(n + 1,0); modInverse[1] = 1; for(int i = 2; i <= n; i++) { modInverse[i] = (-(m/i) * modInverse[m % i]) % m + m; } return modInverse; }