The euclidean algorithm, called the moving phase division, is used to calculate the public factor of known natural numbers m and n. Use the program to explain the specific situation of separation.
First, let's look at Recursive Implementation:
Copy codeThe Code is 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. Take the remainder r for the input two natural numbers m> n, so that 0 <= r <n
2. if r is 0 and n is the result, return directly
3. if r is not 0, m = n, n = r is assigned and re-executed from step 1.
The definitions of the public factors of two natural numbers describe the conditions for the calculation results. If the remainder r calculated in step 1 is 0, the smaller number is the public factor. If r! If the value is 0, the relationship between natural numbers m and n can be expressed as: m = kn + r (where k is a natural number ), equations can prove that any number that can divide m must be able to divide n and r. equations can be further deformed into: r = m-kn, it indicates that at the same time, any number of m and n must be able to divide r. That is to say, the set of numbers that can divide m and n is equal to the set of numbers that divide n and r. So the method of separation is established.
Release another version that cyclically implements the Euclidean algorithm.
Copy codeThe Code is 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;
}