【程序6】
題目:輸入兩個正整數(shù)m和n,求其最大公約數(shù)和最小公倍數(shù)。
package com.share.test01_10;
/**
* 【程序6】題目:<br>
* 輸入兩個正整數(shù)m和n,求其最大公約數(shù)和最小公倍數(shù)。
*
* @author brx
*/
public class Test06 {
public static void main(String[] args) {
test(148, 20);
}
/**
* 思路:<br>
* 先比較兩個數(shù)的大小,用小的數(shù)找最大公約數(shù),用大的數(shù)找最小公倍數(shù)<br>
* 思路1:找最小公倍數(shù)通過遞增判斷去找<br>
* 思路2: 找最小公倍數(shù)通過最大公約數(shù)去找
*
* @param max
* 兩個數(shù)中的大的數(shù)
* @param min
* 兩個數(shù)中的小的數(shù)
* @param lcm
* 最小公倍數(shù)(Least Common Multiple)
* @param gcd
* 最大公約數(shù)(Greatest Common Divisor)
*/
public static void test(int m, int n) {
int max = 0;
int min = 0;
max = m > n ? m : n;
min = m < n ? m : n;
int gcd = min;
for (int i = min; i > 1; i--) {
if (max % i == 0 && min % i == 0) {
System.out.println("最大公約數(shù):" + i);
gcd = i;
break;
}
}
int lcm = max;
while (true) {
if (lcm % max == 0 && lcm % min == 0) {
System.out.println("最小公倍數(shù):" + lcm);
break;
}
lcm++;
}
lcm = max * min / gcd;
System.out.println("最大公倍數(shù):" + lcm);
}
}