Euclid's algorithm is called the Euclidean method, which is used to find the common factor of the known m and n two natural numbers. Combine the procedure to explain the specific situation of the division.
First look at recursive implementations:
Copy Code code as follows:
int getcd (int m,int N)
{
if (M < 0 | | | n <0) {
return 0;
}
if (M < n)
{
int t = m;
m = n;
n = t;
}
if (m% n)
{
Return Getcd (N, (m% n));
}
Else
{
return n;
}
}
The main calculation process is divided into three steps:
1, the input of two natural number M > n to take the remainder R, so that 0<= R < n
2, if R for 0,n is the result of the request, direct return
3, R is not 0, the assignment m=n,n=r starts at step 1 and then executes again
The definition of the common factor of two natural numbers shows the condition of the result of the calculation. If the remainder r = 0 is calculated in step 1, the smaller number is the common factor. If r!=0, the relationship between the natural number m and n can be expressed as: M = kn + R (where k is a natural number), the equation can prove that any number that can divide m must be divisible by N and R; the equation is further deformed to: R = m-kn, which means that any number that divides m and N at the same time is bound to be divisible by R. In other words, the set of numbers that divide m and n is equal to the set of numbers that divide N and R. So the method of dividing the divide is established.
Then publish a loop to implement the Euclidean algorithm version.
Copy Code code as follows:
int getcd2 (int m,int N)
{
if (M < 0 | | | n <0) {
return 0;
}
if (m<n)
{
int t=m;
M=n;
n=t;
}
int cd = 1;
while (1) {
int r = m% n;
if (0==r)
{
cd = n;
Break
}
else {
M=n;
N=r;
}
}
return CD;
}