最大公约数和最小公倍数 in Java

来源:互联网 发布:sql sever设置主键 编辑:程序博客网 时间:2024/06/01 07:54

最近在学校当助教,课程是Java数据结构,因此重温一下算法和数据结构,也因此把算法和一些Java的特性学习的更深刻,也希望用写博客来监督自己的持续学习。

今天介绍的是Java中的最大公约数和最小公倍数的算法。不啰嗦了,直接上代码:

  • 最大公倍数的普通写法
/**     * use for loop to calculate common divisor     * @param x     * @param y     * @return     */    private int maxCommonDivisor(int x, int y) {        // only use loop to deal with the problem        if (x < y) {            int temp = x;            x = y;            y = temp;        }        if (y == 0) {            return x;        }        while (x % y != 0) {            int temp = x % y;            x = y;            y = temp;        }        return y;    }
  • 最大公倍数的递归写法
private int maxCommonDivisorRecursion(int x, int y){         if(x < y){             //make sure x always larger than y             int temp = x;             x = y;             y = temp;         }         if(y ==0){             return x;         }         if(x % y == 0){             //y can divide x             return y;         } else{             //recursion, and set y to new X, set y as m % n             return maxCommonDivisorRecursion(y , x % y);         }    }

得到最大公倍数后,求最小公倍数,只需要使用公式 a*b/(最大公约数),既得所求:

/**     * 使用公式,两数相乘,除以两数的最大公约数,所得结果为最小公倍数     * @param x     * @param y     * @return     */    private int minCommonMultiple(int x, int y){        return x*y/maxCommonDivisor(x,y);    }

References:
[1]http://blog.csdn.net/lwcumt/article/details/8029241
[2]http://www.cnblogs.com/hexiaochun/archive/2012/09/03/2668250.html

0 0
原创粉丝点击