Find the least common multiple and greatest common divisor of two integers java

topic:

Enter two positive integers m and n, and find their greatest common divisor and least common multiple.

Problem-solving ideas

In the loop, as long as the divisor is not equal to 0, divide the larger number by the smaller number, and use the smaller number as the larger number in the next round, and the remainder as the smaller number in the next round. Loop until the value of the smaller number is 0, and return the larger number. This number is the greatest common divisor, and the least common multiple is the product of two numbers divided by the greatest common divisor.

import java.util.*;
public class  commonMultiple{
    
    
	public static void main(String[] args) {
    
    
		int	a,b,m;
		Scanner s = new Scanner(System.in); 
		System.out.print( "键入一个整数: ");
		a = s.nextInt();
		System.out.print( "再键入一个整数: ");
		b = s.nextInt();
		deff cd = new deff();
		m = cd.deff(a,b);
		int n = a * b / m;
		System.out.println("最大公约数: " + m);
		System.out.println("最小公倍数: " + n);
	}
}
class deff{
    
    
	public int deff(int x, int y){
    
    
		int t;
		if(x < y) {
    
    
			t = x;
			x = y;
			y = t;
		}
		while(y != 0) {
    
    
			if(x == y)
				return x;
			else {
    
    
				int k = x % y;
				x = y;
				y = k;
			}
		}
		return x;
	}
}

Guess you like

Origin blog.csdn.net/p715306030/article/details/113928183