**Contextual introduction**

is well known that there is a magic function called gcd, Chinese called the greatest common divisor

algorithm is extremely simple

```
int gcd(int a,int b){
if(!b)return a;
return gcd(b,a%b);
}
```

This approach is often referred to compute gcd removed divided, however, his scientific name is called "Euclidean algorithm"

However, the mathematician Euclid may just want to torture people with a gcd

So, he developed something called exgcd, scientific name "extended Euclidean"

Example: Luo Gu P1082 congruence equation

The equation for seeking the smallest integer x, a * x mod b = 1 Solution

**Is transformed**

We observed that the subject of this equation, his essence is to seek ax + by = 1 this equation is the smallest integer solution

Where y is an integer from our newly introduced, and my son seems to be a negative number. It said this is to use Extended Euclidean Algorithm. We will strive to find a set of x, y to satisfy this equation.

See here, it may be in doubt: the extended Euclidean is used to find the ax + by = gcd (a, b) unknowns, how involved is equal to 1 it?

The principle is the equation ax + by = max + by = m solvability is essential m mod gcd (a, b) = 0.

Defined by the greatest common factor, it is a known multiple of GCD (a, b), and b is a multiple of GCD (a, b), and

If x, y are integers, it is determined that the ax + by a multiple of gcd (a, b), and

Since m = ax + by, it must be a multiple m gcd (a, b), and

Then m mod gcd (a, b) = 0

This question can be derived in the equation ax + by = solvability is a necessary condition for 1 mod gcd (a, b) = 0. Therefore, gcd (a, b) is equal to only 1 a. This is in fact a, b coprime

**Extended Euclid**

Extended Euclid, referred to as the expansion of the EU, it is the basis for the foundation to achieve Euclidean algorithm (gcd) on

Code:

```
# include <cstdio>
using namespace std;
int a,b,x,y,k;
void exgcd(int a,int b)
{
if(b==0)
{
x=1;
y=0;
return;
}
exgcd(b,a%b);
k=x;
x=y;
y=k-a/b*y;
return;
}
```

What is the final output of it?

X course, but because you want to mod a number

~~so we have to output x% b~~

wrong, and then think better of

x there may be negative, so we have to output (x + b)% b

Done

**summary**

Extended Euclid is a very common inverse element method

Of course, you might have to ask, above you talk so much, and inverse seeking nothing ah

~~The final output is the inverse ah~~