title: Java实现:求两个数的最大公约数
tags:
- java
- 算法
categories: 个人笔记
copyright: true
abbrlink: f202
date: 2019-12-07 16:44:58
求解两个数的最大公约数的几种方法的比较
1. 暴力枚举法
-
优点:思路简单
-
缺点:运算次数多,效率低
-
极端例子:求1000和10001的最大公约数
需要计算1000/2 - 1 = 4999次
// 暴力枚举法
public static int getGreatestCommonDivisor(int a,int b) {
int big = a > b ? a : b;
int small = a < b ? a : b;
if (big % small == 0) {
return small;
}
for (int i = small / 2; i > 1; i--) {
if (big % i == 0 && small % i == 0) {
return i;
}
}
return 1;
}
2. 辗转相除法
- 优点:运算次数少
- 确定:模运算的开销较大
// 辗转相除法
public static int getGreatestCommonDivisor2(int a, int b) {
int big = a > b ? a : b;
int small = a < b ? a : b;
if (big % small == 0) {
return small;
}
return getGreatestCommonDivisor2(big % small, small);
}
3. 更相减损法
- 优点:避免了取模运算,采用减法运算,开销较小
- 缺点:算法性能不稳定,运算次数多
- 极端例子:两数相差悬殊时,如求1和10001的最大公约数,需要递归9999次
// 更相减损法
public static int getGreatestCommonDivisor3