首页 > 其他 > 详细

想一下,最大公约数怎么求

时间:2017-12-04 23:03:43      阅读:227      评论:0      收藏:0      [点我收藏+]

1.辗转相除法

/**
     * 辗转相除法,a和b都很大时,运算的次数就会越多
     * @param a
     * @param b
     * @return
     */
    public static int test1(int a,int b){
        int max=a>b?a:b;
        int min=a<b?a:b;
        int c =max%min;
        if(c==0){
            return min;
        }
        return test1(c,min);
    }

2.更相减损术

 /**
     * 更相减损术,a和b数相差太大,可能导致递归的时间越来越长
     * @param a
     * @param b
     * @return
     */
    public static int test2(int a,int b){
        int max=a>b?a:b;
        int min=a<b?a:b;
        int c=max-min;
        if(c==0){
            return min;
        }
        return test2(c,min);
    }

3.神奇的第三种(前面两种的结合)

/**
     * 上面的结合体,采用移位的方法
     * @param a
     * @param b
     * @return
     */
    public static int test3(int a,int b){
       if(a==b){
           return b;
       }
       if(a<b){
           return test3(b,a);
       }
       if(a%2==0&&b%2==0){
           return test3(a>>1,b>>1);
       }else if(a%2==0&&b%2!=0){
           return test3(a>>1,a-b);
       }else if(a%2!=0&&b%2==0){
           return test3(a-b,b>>1);
       }else{
           return test3(a,a-b);
       }
    }

为什么一个简单的问题,要究其所以然呢?

想一下,最大公约数怎么求

原文:http://www.cnblogs.com/huhu1203/p/7979367.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!