/*
-
求最大公约数
-
1.更相减法
-
2.辗转相除法
-
3.穷举法
*/
public class Gcd {public static void main(String[] args) {
// TODO Auto-generated method stubint a = 24, b = 15; System.out.println("The method1' result is " + gcd1(a, b)); System.out.println("The method2' result is " + gcd2(a, b)); System.out.println(); int a1 = 91, b1 = 49; System.out.println("The method1' result is " + gcd1(a1, b1)); System.out.println("The method2' result is " + gcd2(a1, b1));
}
/*
- 更相减法:大的 - 小的
- 若s=a-b,则gcd(a,b)=gcd(b,s),当b等于s时结束
*/
public static int gcd1(int num1, int num2) {int n1 = Math.max(num1, num2); int n2 = Math.min(num1, num2); while ( n1 != n2) { int tmp = n1 - n2; n1 = Math.max(n2, tmp); n2 = Math.min(n2, tmp); } return n2;
}
/*
- 辗转相除法:大的 ÷ 小的
- 若r=a%b,则gcd(a,b)=gcd(b,r),当r=0时,循环结束
*/
public static int gcd2(int num1, int num2) {
int n1 = Math.max(num1, num2); int n2 = Math.min(num1, num2); int r = n1 % n2; while (r != 0) { n1 = n2; n2 = r; r = n1 % n2; } return n2;
}
}