Java求最大公约数

介绍第一种容易想到的:

//任意输入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));
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值