There are two algorithms for finding the maximum common divisor of two integers: The moving Subtraction Method and the moving division method. The idea of these two algorithms is to make the two integers continuously subtract the multiples of the maximum common divisor. The end condition of the moving and subtraction operation is that the two integers are equal. At this time, the values of these two numbers are the maximum public approx. The ending condition of the moving phase division is that the modulo of two numbers is equal to zero, that is, when one number can be divided by another, the smaller number is the maximum common number. These two algorithms are implemented using recursion and non-recursion respectively. The program is implemented in C language and has been deployed in Visual C ++ 6.0
The code is not very concise, so I will share my learning experience with you!
# Include <stdio. h>
/* Returns the maximum common divisor of two integers -- Recursive Implementation of the moving and Subtraction Method */
/* Int greatcommondivisor (INT num1, int num2)
{
If (num1> num2)
Returns greatcommondivisor (num1-num2, num2 );
Else if (num1 <num2)
Return greatcommondivisor (num1, num2-num1 );
Else
Return num1;
}*/
/* Returns the maximum common divisor of two integers-non-Recursive Implementation of the moving-to-Subtraction Method */
/* Int greatcommondivisor (INT num1, int num2)
{
While (1)
{
If (num1> num2)
Num1-= num2;
Else if (num1 <num2)
Num2-= num1;
Else
Return num1;
}
}*/
/* Returns the maximum common divisor of two integers-non-Recursive Implementation of the moving phase division */
/* Int greatcommondivisor (INT num1, int num2)
{
While (num1 * num2! = 0)
{
If (num1> num2)
Num1 % = num2;
Else
Num2 % = num1;
}
Return (num1 = 0? Num2: num1 );
}*/
/* Returns the maximum common divisor of two integers -- Recursive Implementation of the moving phase division */
Int greatcommondivisor (INT num1, int num2)
{
If (num1 * num2 = 0)
Return (num1 = 0? Num2: num1 );
If (num1> num2)
Return greatcommondivisor (num1% num2, num2 );
Else if (num1 <num2)
Return greatcommondivisor (num2% num1, num1 );
}
Void main ()
{
Int A = 14;
Int B = 21;
Int result = greatcommondivisor (A, B );
Printf ("% d/N", result );
}