Title Description
Find the greatest common divisor of integers a and B.
Problem analysis
The so-called greatest common divisor of the integer A, b, is to satisfy the a%c=0, b%c=0 the largest positive integer c, that is, to be able to divide a and b at the same time the largest positive integer c.
Brute Force enumeration
If both A and B are not 0, then iterate through all positive integers not greater than a (or b), and then test whether it satisfies both, and selects the largest one in all positive integers satisfying the two.
If a, b one of which is 0, then greatest common divisor is a, B is the one of non-zero;
If both A and B are 0, then greatest common divisor does not exist (any number can be divisible at the same time).
Note: When a and B values are large (such as 100000000), the algorithm takes more time.
Euclidean algorithm (also known as the Division method)
If A and B are all 0, then their greatest common divisor does not exist; If A and B are 0, then their greatest common divisor is not 0; If A and B are not 0, the new a=b is made; the new b=a%b then repeats the process.
Description: The proof process is shown at the bottom.
Recursive implementation of code implementation
#include <iostream>using namespace Std;int gcd (int a, int b) {if (a = = 0 && b = = 0) return-1;//Not present//A, B is negative , the absolute value is obtained first, then the greatest common divisor if (a < 0) a =-a;if (b < 0) B =-b;if (b = = 0) return A;return gcd (b, a%b);} int main () {int m, n;while (Cin >> m >> N) {cout << gcd (M, n) << Endl;} return 0;}
Loop implementation
#include <iostream>using namespace Std;int gcd (int a, int b) {if (a = = 0 && b = = 0) return-1;//Not present//A, B is negative , the absolute value is obtained first, then the greatest common divisor if (a < 0) a =-a;if (b < 0) B =-b;while (b! = 0) {int t = A%b;a = B;b = t;} return A;} int main () {int m, n;while (Cin >> m >> N) {cout << gcd (M, n) << Endl;} return 0;}
Euclidean algorithm proves
1> the number of conventions of a, b and also of B, a mod b
2> proves that if G is the largest convention number of A and B, it is also the largest number of conventions for B, a mod b
We assume that G is a, B greatest common divisor, but it's not a greatest common divisor of B, a mod B,
Greatest common divisor (GCD)