0 , Euclid's theorem
The basis of all, nature is Euclidean theorem. Its form is very simple (sometimes naive)
gcd (A, a) =gcd (b,a mod b)
Prove:
Suppose a , the number of conventions for B is g, and $${a}={bx+y}{(x,y\in Z)}$$
There is obviously $${g \mid A},\qquad {g \mid b},\ Qquad{{a}\ mod\ {b}}={y}$$
$${\because g \mid b}$$
$${\therefore g \mid bx}$$
and $${\ Because G \mid a}$$
$${\therefore g \mid {(A-BX)}}$$
i.e. $${g \mid {{a}\ mod\ {b}}}$$
so g is b and a mod b the number of conventions
that is (A, B) The number of conventions for and (b,a mod b) is the same, so their greatest common divisor are the same.
- Euclidean algorithm
aka "the division of the Law", is the current general algorithm for greatest common divisor, to achieve a simple function powerful. (The code can be said to be very beautiful)
int gcd ( int x, int y) { return y? GCD (Y, x%y): x;}
a mod b is necessarily less than, the last B becomes a, the last a mod B becomes B, so the worst case is O (log n) .
- Bezout theorem
Before introducing the extended Euclidean theorem, we first need to introduce the bezout theorem (Bézout theorem, bezout theorem).
Bezout theorem: If ${ax+by=z}$, then there is $${GCD (A, b)}\mid{z}$$
Bezout theorem Expansion: If ${a_1x_1+a_2x_2+...+a_nx_n}=z$, there is $${GCD (a_1,a_2,..., a_n)}\mid{z}$$
- extended Euclidean algorithm
The extended Euclidean algorithm is very powerful and can be used to find the general solution of a two-yuan equation.
Obviously when $b =0$, $GCD (A, b) =a$. At this point $x =1,y=0$
When $a>b>0$
Set $ $ax _1+BY_1=GCD (A, b) $$
$${bx_2}+{({a}\ mod\ {b}) y_2}={gcd (b,{a}\ mod\ {b})}$$
By Euclidean theorem, $ $gcd (A, B) =gcd (b,{{a}\ mod\}) $$
Then: $ $ax _1+by_1=bx_2+{({a}\ mod\ {b}) y_2}$$
That is, $ $ax _1+by_1=ay_2+b (X_2-{[{a}/{b}]}{\times} y_2) $$
According to the identity theorem: $${x_1=y_2},\qquad{y_1=x_2-{[{a}/{b}]}{\times} y_2}$$
This gives us a way to solve ${x_1},{y_1}$: The value of ${x_1},{y_1}$ is based on ${x_2},{y_2}$
By Bezout theorem We know: ${ax+by=z}$,z is gcd (A, B) several times, so we first solve ${AX+BY={GCD (A, B)}}$, and then multiply the solution by ${{Z}/{GCD (A, b)}}$. (The above '/' means divisible)
CPP Code:
int exgcd (intint int int y) { int d = A; if 0 {= EXGCD (b, a%B, y, x); -= (A/b) *x; } Else { 10; } return D;}
Extended Euclidean algorithm