/**
*
* 求最大公约数
*
*/
public class GreatestCommonDivisor {
/**
* f(x,y) = f(y,x%y)
*/
static int gcd(int x, int y) {
if (y == 0) {
return x;
}
return gcd(y, x % y);
}
/**
* f(x,y) = f(x-y,y)
*/
static int gcd2(int x, int y) {
if (x == 0) {
return y;
}
if (y == 0) {
return x;
}
if (x < y) {
return gcd2(y - x, x);
} else {
return gcd2(x - y, y);
}
}
public static void main(String[] args) {
System.out.println(gcd2(30, 40));
System.out.println(gcd(40, 30));
}
}
求两个数的最大公约数
最新推荐文章于 2021-05-17 00:02:39 发布