最大公約數(shù)[1]
①定義
幾個自然數(shù)公有的約數(shù),叫做這幾個數(shù)的公約數(shù);其中最大的一個,叫做這幾個數(shù)的最大公約數(shù)。
②輾轉(zhuǎn)相除法
又稱“歐幾里得算法”,是求最大公約數(shù)的算法
求兩個數(shù)的最大公約數(shù):如果m > n,令余數(shù)remainder = m%n,如果余數(shù)不為0,則令m = n, n = remainder,再次remainder = m%n,直到remainder = 0,此時n就是最大公約數(shù)。
求多個數(shù)的最大公約數(shù):先求出其中兩個數(shù)的最大公約數(shù),再求這個最大公約數(shù)與第三個數(shù)的最大公約數(shù),依次求下去,直到最后一個為止,最后所得的那個最大公約數(shù),就是所求的幾個數(shù)的最大公約數(shù)
③代碼實現(xiàn)[2]
public static int maxCommonDivisor(int m, int n) {
if (m < n) { // 保證被除數(shù)大于除數(shù)
int temp = m;
m = n;
n = temp;
}
while (m % n != 0) { // 在余數(shù)不能為0時,進行循環(huán)
int temp = m % n;
m = n;
n = temp;
}
return n; // 返回最大公約數(shù)
}
最小公倍數(shù)
①定義
兩個或多個整數(shù)公有的倍數(shù)叫做它們的公倍數(shù),其中除0以外最小的一個公倍數(shù)就叫做這幾個整數(shù)的最小公倍數(shù)[3]
②短除算法
兩個數(shù)相乘等于這兩個數(shù)的最大公約數(shù)和最小公倍數(shù)的積。
③代碼實現(xiàn)
public static int minCommonMultiple(int m, int n) {
return m * n / maxCommonDivisor(m, n);
}
參考文獻
[1] Java求最大公約數(shù)與最小公倍數(shù)
[2] Java求最大公約數(shù)和最小公倍數(shù)
[3] 百度百科——最小公倍數(shù)