Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - Using JAVA to realize the programming of finding the greatest common divisor of two positive integers. Tangible interface
Using JAVA to realize the programming of finding the greatest common divisor of two positive integers. Tangible interface
The following code is a tool class for calculating the greatest common divisor and the least common multiple. Among them, there are two methods to solve the greatest common divisor: recursive method and cyclic method.

Import java.util. *;

/* Find the greatest common divisor and the least common multiple */

Public class maxcommondivisorandmincommonmultiple {

Public static void main(String[] args) {

Scanner scan = new scanner (system. in); //Receive information input from the console.

System.out.print ("Please enter the first integer:");

int num 1 = scan . nextint(); //Take out the information entered by the console.

System.out.print ("Please enter the second integer:");

int num 2 = scan . nextint(); //Take out the information entered by the console.

system . out . println(maxCommonDivisor(num 1,num 2)); //Call the maxCommonDivisor () method.

system . out . println(minCommonMultiple(num 1,num 2)); //Call the minCommonMultiple () method

}

//Recursive method for finding the greatest common divisor

public static int maxcommon divisor(int m,int n) {

If (m & ltN) {// m>N is guaranteed, if m < N, data exchange will be carried out.

int temp = m;

m = n;

N = temperature;

}

If (m% n == 0) {// If the remainder is 0, the greatest common divisor is returned.

Returns n;

} else {// Otherwise, recursively assign n to m and assign the remainder to n..

Returns maxcommandivisor (n, m% n);

}

}

//Find the greatest common divisor by cyclic method

public static int maxcommondivisor 2(int m,int n) {

If (m & ltN) {// m>N is guaranteed, if m < N, data exchange will be carried out.

int temp = m;

m = n;

N = temperature;

}

while (m % n! = 0) {// When the remainder cannot be 0, loop.

int temp = m % n;

m = n;

N = temperature;

}

Returns n; //Returns the greatest common divisor

}

//Find the least common multiple

public static int minCommonMultiple(int m,int n) {

Returns m * n/maxcommandivisor (m, n);

}

}