JAVA算法基础 求最大公约数和最小公倍数

时间:2021-05-05 00:30:57

JAVA算法基础 求最大公约数和最小公倍数

import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int m = Integer.parseInt(sc.next());
int n = Integer.parseInt(sc.next());
System.out.println("最大公约数:"+getMaxCommonDivisor(m,n));
System.out.println("最小公倍数:"+getMinCommonMultiple(m,n));
}
}

public static int getMaxCommonDivisor(int m,int n){
if(m<n){ //保证m>n
int temp = m;
m = n;
n = temp;
}
while(m%n!=0){
int temp = m%n;
m=n;
n=temp;
}
return n;
}

public static int getMinCommonMultiple(int m,int n){
return m*n/getMaxCommonDivisor(m,n);
}
}