Euclidean algorithm
Task
Find the greatest common divisor gcd(a, b) of two integers a and b.
Explanation
By Bézout’s identity [if a and b are integers, there exist integers x and y such that ax + by = gcd(a, b)], we have gcd(a, b) = gcd(b, a - b) with a ≥ b. Iterating like this until b = 0 yields the gcd of the original pair. Pure subtraction would be too slow, so observe that while a - b is still larger than b the same operation runs again — we can subtract b from a until a is smaller than b. Hence gcd(a, b) = gcd(b, a mod b), which finds the gcd in logarithmic time.
Prototype
int gcd(int a, int b);
Complexity
O(log N), where N is on the same order as a and b.
Input
Two integers a and b.
Output
The gcd of a and b.
Code
| |
Extended Euclidean algorithm
Task
Find the gcd of A and B, and find X and Y such that AX + BY = GCD(A, B).
Explanation
We need X and Y satisfying AX + BY = GCD(A, B). When B = 0, X = 1 and Y = 0 do the job. When B > 0, building on the Euclidean algorithm, we know: GCD(A, B) = GCD(B, A mod B) First recurse to obtain X’ and Y’ satisfying: B X’ + (A mod B) Y’ = GCD(B, A mod B) = GCD(A, B) Then expand and work backwards: B X’ + (A - A/BB) Y’ = GCD(A, B) A Y’ + B X’ - (A/B)B Y’ = GCD(A, B) Here the division is integer division. Collecting the terms that contain B: A Y’ + B (X’ - A/BY’) = GCD(A, B) Therefore X = Y’, Y = X’ - A/BY'
Prototype
int extend_gcd(int a, int b, int &x, int &y);
Complexity
O(log N), where N is on the same order as a and b.
Input
Two integers a and b, plus the references &x and &y for one solution of ax + by = GCD(a, b).
Output
The gcd of a and b; after the call, x and y satisfy ax + by = GCD(a, b).
Code
| |
References
ACM International Collegiate Programming Contest: Algorithms and Implementations Baidu Baike