How to find the inverse element

multiplicative inverse

For the elements in the reduced system, each number a has a unique multiplicative inverse element x corresponding to it, so that
a sufficient and necessary condition for a number ax≡1(mod n) to have an inverse element is gcd(a,n)=1 , at this time the only
inverse The meaning of the inverse element: in the sense of modulo n, if a number a has an inverse element x, then dividing by a is equivalent to multiplying by x.

 

 

Here are several methods for finding the inverse:

1. Extended Euclidean

Given the modulus m, finding the inverse of a is equivalent to solving ax=1(mod m).
This equation can be transformed into ax-my=1
and then apply the method of finding the quadratic linear equation, and use the extended Euclidean algorithm to find a Group x0, y0 and gcd
to check whether gcd is 1.
If gcd is not 1, it means that the inverse element does not exist.
If it is 1, adjust x0 to the range of 0~m-1.

 

1 ll extgcd(ll a, ll b, ll& x, ll& y)
 2  // solve ax+by=gcd(a, b)
 3  // return value gcd(a, b) 
4  {
 5      ll d = a;
 6      if (b)
 7      {
 8          d = extgcd(b, a % b, y, x);
 9          y -= (a / b) * x;
 10      }
 11      else x = 1 , y = 0 ;
 12      return d ;
 13  }
 14  ll mod_inverse(ll a, ll m)
 15  // Solve the inverse of a with respect to m on modulo 
16 {
17     ll x, y;
18     extgcd(a, m, x, y);
19     return (m + x % m) % m;
20 }

 

2. Fermat's little theorem

In the case where the modulus is prime p, there is Fermat's little theorem
a^(p-1)=1(mod p)
then a^(p-2)=a^-1(mod p)
that is the inverse of a The element is a^(p-2)

In the case where the modulus is not a prime number p, there is Euler's theorem
a^phi(m)=1 (mod m) (a⊥m)
Similarly a^-1=a^(phi(m)-1)

Therefore, the inverse element x can be obtained by applying fast exponentiation to x=a^(phi(m)-1)

But there seems to be a problem? How to judge whether a has an inverse element? 

Check the properties of the inverse element to see if the multiplied power value x and a is 1.

PS: The complexity of this algorithm is O(log2N) in several tests, the constant seems to be larger than the previous method

When p is relatively large, it is necessary to use fast power to solve

There are also inverse yuan playing the table and special circumstances, and then I will sort it out after sitting down on the topic.

https://blog.csdn.net/guhaiteng/article/details/52123385

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326482573&siteId=291194637