public class GreatestCommonDivisor {
public static void main(String[] args) {
GreatestCommonDivisor divisor = new GreatestCommonDivisor();
System.out.println(divisor.getForMethodOne(15, 25));
System.out.println(divisor.getForMethodTwo(16, 24));
System.out.println(divisor.getForMethodThree(16, 24));
System.out.println(divisor.gcd(16, 24));
}
//辗转相除法 欧几里得算法
//a = kb + r,如果d是a,b的约数,那么d一定是也是r约数
private int getForMethodTwo(int a, int b) {
int big = Math.max(a, b);
int small = Math.min(a, b);
if (big % small == 0) {
return small;
}
return getForMethodTwo(big % small, small);
}
//更相减损术
//a = b + r,如果d是a,b的约数,那么d一定是r的约数
private int getForMethodThree(int a, int b) {
int big = Math.max(a, b);
int small = Math.min(a, b);
if (big % small == 0) {
return small;
}
return getForMethodThree(big - small, small);
}
//移位算法
private int gcd(int a, int b) {
if (a == b) {
//相等时为最大公约数
return a;
}
if ((a & 1) == 0 && (b & 1) == 0) {
//a,b均为偶数
return gcd(a >> 1, b >> 1) << 1;
} else if ((a & 1) == 0 && (b & 1) != 0) {
//a偶数,b奇数
return gcd(a >> 1, b);
} else if ((a & 1) != 0 && (b & 1) == 0) {
//a奇数,b偶数
return gcd(a, b >> 1);
} else {
//a,b均为奇数
int big = a > b ? a : b;
int small = a < b ? a : b;
//两个奇数的差必为偶数
return gcd(big - small, small);
}
}
//时间复杂度为O(n)
private int getForMethodOne(int a, int b) {
int big = Math.max(a, b);
int small = Math.min(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;
}
}
求两数的最大公约数
最新推荐文章于 2023-07-28 07:10:27 发布