Problem description: calculate the maximum common divisor of two positive integers.
Train of Thought: This is a very basic problem. The most common is the two methods, namely the moving and division method and the moving and Subtraction Method. The general formula is f (x, y) = f (y, X % Y), F (x, y) = f (y, x-y) (x> = Y> 0 ). It is not difficult to write an algorithm based on the general expression. I will not give it here. The algorithms in the beauty of programming are provided here to reduce the number of iterations.
For X and Y, if y = K * Y1, x = K * X1, f (x, y) = K * F (x1, Y1 ). In addition, if X = p * X1, assume that p is a prime number and Y % P! = 0, then f (x, y) = f (p * X1, y) = f (x1, Y ). Take P = 2.
Reference code:
// Function: calculate the maximum common approx. // function parameter: X and Y are two values // return value: int gcd_solution1 (int x, int y) {If (y = 0) return X; else if (x <Y) return gcd_solution1 (Y, x); else {If (X & 1) // X is an odd {If (Y & 1) // y is an odd return gcd_solution1 (Y, x-y); else // y is an even return gcd_solution1 (X, y> 1);} else // X is an even number {If (Y & 1) // y is an odd number return gcd_solution1 (x> 1, y ); else // y is an even return gcd_solution1 (x> 1, Y> 1) <1 ;}}}
The following non-recursive versions:
int gcd_solution2(int x, int y){int result = 1;while(y){int t = x;if(x&1){if(y&1){x = y;y = t % y;}elsey >>= 1;}else{if(y&1)x >>= 1;else{x >>= 1;y >>= 1;result <<= 1;}}}return result * x;}