GCD of two positive integers
Train of thought: This is a very basic problem, the most common is two methods, Euclidean method and subtraction. The formula is f (x, y) = f (y, x%y), f (x, y) = f (y, XY) (x >=y > 0). It is not difficult to write an algorithm according to the formula, which is not given here. Here is the "beauty of programming" algorithm, mainly to reduce the number of iterations.
For x and y, if y = k * y1, x= k * X1, then f (x, y) = k * F (x1, y1). In addition, if x = p * x1, assuming P is prime and y% p!= 0, then f (x, y) = f (p * x1, y) = f (x1, y). Take P = 2.
Reference code:
function function: Find GCD
//function parameter: X,y is two number
//return value: gcd
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 odd
{
if (y&1)//y is odd return
gcd_solution1 (y, xy);
Else //y is an even return
gcd_solution1 (x, y>>1)
;
Else//x is an even
{
if (y&1)//y is an odd return
Gcd_solution1 (x>>1, y);
Else //y is an even return
Gcd_solution1 (x>>1, y>>1) << 1
}
}
}
Ask LCM:
The most commonly used is the Euclidean method, which has two integers a and B:
①a%b to the remainder C
② if c=0, then B is two number of GCD
③ if c≠0, then a=b,b=c, then go back to execute ①
The following are not 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;
}
else
y >>= 1;
}
else
{
if (y&1)
x >>= 1;
else
{
x >>= 1;
Y >>= 1;
Result <<= 1;
}} return result * x;
}