Order
The most commonly used algorithm for greatest common divisor is Euclid's algorithm, also known as the Euclidean method. The problem is defined as the greatest common divisor gcd (i,j) for I and J, where I and j are integers and may be set to i>j.
The algorithm can be expressed recursively:
1. If j can divide I, then gcd (i,j) =j;
2. J cannot divide the I, make r=i%j, then gcd (i,j) =GCD (j,r).
C implementation
int gcd (intint j) { int r = i% j; return 0 ? J:GCD (J, R);}
Analysis
Step 1 of the algorithm, apparently established (greatest common divisor definition);
To prove step 2:
Set D is the greatest common divisor of I and J,
So I=md,j=nd,m and n coprime (otherwise D is not greatest common divisor).
I=kj+r,k=⌊m/n⌋,k≥1 can be obtained by R=I%J (we have previously assumed i>j).
Put the i=md,j=nd in the Get
Md=knd+r
So
R= (M-KN) d
M-kn and M are also coprime.
So get D is the greatest common divisor of J and R.
Time Complexity Analysis:
The inverse of the algorithm, the final remainder is 0, the second-to-last remainder is D, the third time to the penultimate is kd,k>1 ...
Because of the formation of a sequence, {0,d,kd,nkd+d,...}
The n term of the series plus the n+1 term is smaller than the n+2 term, so it is faster than the Fibonacci sequence.
We know that the Fibonacci sequence growth rate is exponential, and the number of columns to be analyzed is exponential.
The Euclidean algorithm needs k times, then J=o (2^k), then K=o (LG J).
So Euclidean algorithm greatest common divisor time complexity is the order of magnitude, the speed is very fast.
To divide and seek greatest common divisor