First, Euclidean algorithm
The name is very tall on the not necessarily difficult, such as Euclid algorithm ... In fact, it is to ask for two positive integers a, B's greatest common divisor (ie, gcd), also known as the Euclidean method
Need to know a theorem first:
GCD (A, b) = gcd (b, a mod b) (where a mod b! = 0) or b (where a mod b = = 0)
Prove:
The second half of it ... It's nonsense, so just prove the first half.
g = gcd (A, b) may be set, so there is a = G * A, B = g * B and (A, b) = 1
So gcd (b, a mod b) = gcd (G * B, (g * a) mod (G * b)) = G * GCD (b, a mod b)
If gcd (b, A mod b)! = 1, we can get:
Exists g ' > 1, so that G ' | B and G ' | A MoD B, so G ' | A, with (A, B) = 1 Contradiction!
So gcd (b, a mod b) = 1, also known as GCD (b, a mod b) = g * 1 = g = gcd (A, B)
The Certificate of Completion ... (It seems annoying?) )
So you can do it ... Time complexity is O (log (max (A, b)))
Very simple code: (Only one line ...) )
1 int gcd (intint b) {2 return !b? A:GCD (b, a% b); 3 }
View Code
Application words ... In addition to seeking gcd (A, b) ...
It seems to be possible to find a B least common multiple LCM (A, b) = A * B/GCD (A, B) (nonsense +1 ...). )
But many places are used to get gcd ... It's kind of important.
Second, expand Euclidean algorithm
Now, we've already asked for GCD (A, b) ...
And at the same time there is a bezout theorem called "Baked potatoes" like eating ... Hungry >.< mmm):
If GCD (A, b) = 1, then there is x, Y, so a * x + b * y = 1 (Card)
Change it into a:
For any A and B, there is x, Y, so a * x + b * y = gcd (A, B)
The calculation of x, Y can be done in the above solution gcd (A, b) ... Push it out. (There will be a deeper memory)
Please refer directly to code:
1 intEXTEND_GCD (intAintBint&x,int&y) {2 if(!b) {3x =1, y =0;4 returnA;5 }6 intres = EXTEND_GCD (b, a% B, x, y), tmp =x;7x =y;8y = tmp-a/b *y;9 returnRes;Ten}
View Code
and the finding (x, y) is likely to be large (small) very outrageous, so it needs to be adjusted ...
The general solution form of indefinite equation everybody will ...
The application of the extended Euclidean algorithm mainly has the following three aspects:
(1) Solving the indefinite equation
(2) modulo linear equation (linearity with congruence)
(3) Inverse element of the model
As a review of Noip ... (1) is the original usefulness, (2) (3) should not be said to test (strange flag)
A summary of Noip knowledge points--Euclid algorithm and extended Euclidean algorithm