介绍第一种容易想到的:
//任意输入2个整数,求他们的最大公约数?
//什么是最大公约数,最大公约数是指两个或多个约数中最大的一个
//( 最大公约数,也称最大公因数,指两个或多个整数共有约数中最大的一个。)
//举个例子10 和 40的最大公约数是什么?
/*
10的约数有 1*10 2*5
40的约数有 1*40 2*20 4*10 5*8 这些因子都是他的约数
再找出他们公共的因数是1 2 5 10
我们发现他们的最大的公约数是10
如果a=8,b=6;
则8:1 2 4 8
6 :1 2 3 6
如6和12
6的因数有1,2,3,6;
12的因数有1,2,3,4,6,12;
他们的公共的因数是 1 2 3 6
它们最大公约数是6
*/
public class text6{
public static void main (String [] args) {
int flag = sum(6,12);
System.out.println(flag);
}
public static int sum (int a,int b) {
int big = a>b ? a : b;
int small= a< b ? a:b ;
if (a%b==0){
return small;
}
for ( int i=small /2;i>1 ;i-- ) {
if (small%i==0&&big%i==0){
return i;
}
}
return 1;
}
}
第二种:利用方法循环调用相减找出最大公约数
public static int getGreatestCommonDivisorV3(int a, int b){
if(a == b){
return a;
}
int big = a>b ? a:b;
int small = a<b ? a:b;
return getGreatestCommonDivisorV3(big-small, small);
}
public static void main(String[] args) {
System.out.println(getGreatestCommonDivisorV3(25, 5));
System.out.println(getGreatestCommonDivisorV3(100, 80));
System.out.println(getGreatestCommonDivisorV3(27, 14));
}
第三种:利用方法调用辗转相除找出最大公约数
public static int getGreatestCommonDivisorV2(int a, int b){
int big = a>b ? a:b;
int small = a<b ? a:b;
if(big%small == 0){
return small;
}
return getGreatestCommonDivisorV2(big%small, small);
}
public static void main(String[] args) {
System.out.println(getGreatestCommonDivisorV2(25, 5));
System.out.println(getGreatestCommonDivisorV2(100, 80));
System.out.println(getGreatestCommonDivisorV2(27, 14));
}