The functions in this tip find the greatest common divisor (GCD) or the least common multiple (LCM) of two given integers.
Getting the GCD through recursion:
int GCD(int x,int y)
{
if(y==0) // base case, the programs stops if y reaches 0.
return x; //it returns the GCD
else
return GCD(y,x%y); //if y doesn't reach 0 then recursion continues
}
Suppose x=80 and y=100:
x y
-------------
80 100
100 20
20 0
The GCD function shown above returns 20 as the GCD of the two given integers.
Getting the GCD through iteration:
Using the While Loop:
int GCD(int x,int y)
{
int t;
while (y!=0)
{
t=y;
y=x%y;
x=t;
}
return x;
}
Suppose x=80 and y=100:
x y t
-----------------------
80 100 20
100 20 0
20 0
x y i
-----------------------
80 100 79
80 100 78
80 100 77
|
80 100 20
80%20==0 && 100%20==0
Then 20 is the GCD.
Getting the LCM through recursion:
int LCM(int x,int y)
{
int prod;
if(y%x==0)
return y;
else
{
prod=x*y;
while(x!=y) // get the GCD of 2 given integers
{
if(x>y)
x=x-y;
else
y=y-x; //x now is the GCD
}
return LCM(y,prod/x); //recurse, changing x to y and vice versa
} //LCM = (x*y)/(GCD)
}