Greatest common divisor has the following two ways:
method of dividing: Span style= "LINE-HEIGHT:24PX; Text-indent:28px "> aka Euclid algorithm (Euclidean algorithm) is an algorithm for finding the greatest common divisor of two positive integers.
toss and subtract: Span style= "LINE-HEIGHT:24PX; Text-indent:28px "", Nikoman the law greatest common divisor
Below are Java Code:
Public class Javabase
{
static public int gcd1_1 (int x, int y) // Non-recursive method of dividing
{
int temp ;
do{
temp = x% y;
x = y;
y = temp;
}while (temp! = 0);
return x ;
}
static public int gcd2_1 (int x, int y) // non-recursive subtraction
{
int max, min;
int temp ;
max = (x > y)? x:y;
min = (x < y)? x:y;
while (max! = min)
{
temp = max-min;
max = (temp > min)? temp:min;
min = (temp < min)? temp:min;
}
return Max ;
}
static public int gcd1_2 (int x, int y) // recursive method of dividing
{
return (y = = 0) x:gcd1_2 (y, x% y);
}
static public int gcd2_2 (int x, int y) // recursive subtraction
{
if (x = = y) return x;
return (x > Y) gcd2_2 (xy, y): gcd2_2 (x, y-x);
}
public static void Main (String args[])
{
int a = +, B =-;
int g = 0;
g = Gcd1_1 (A, b);
System.out.println ("greatest common divisor for:" + g);
g = Gcd1_2 (A, b);
System.out.println ("greatest common divisor for:" + g);
g = Gcd2_1 (A, b);
System.out.println ("greatest common divisor for:" + g);
g = Gcd2_2 (A, b);
System.out.println ("greatest common divisor for:" + g);
System.out.println ("least common multiple for:" + A * b/g); // least common multiple
}
Java greatest common divisor and least common multiple