日期:2014-05-20  浏览次数:20673 次

在JAVA中如何实现求最大公约数和最小公倍数
题目中没有具体是两个数还是几个数。

------解决方案--------------------
写个求两个数的公约数或公倍数的方法。
把要求的数全部放到数组里
迭代的把所有数两个两个的放到方法里求并返回结果,并把结果再拿去求
------解决方案--------------------
先比较两个数的大小,在用大的取于较小的数,将较小的数作为下一轮较大的数,余数作为较小的数如此循环,到余数为零返回较大的数, 此数为最大公约数,把两数相成除以最大公约数就是最小公倍数了。
------解决方案--------------------
import java.util.*;
public class pxl_1012 { 
public static void main(String[] args) {
int a ,b,m;
Scanner s = new Scanner(System.in);
System.out.print( "键入一个整数: "); 
a = s.nextInt();
System.out.print( "再键入一个整数: "); 
b = s.nextInt();
deff cd = new deff();
m = cd.deff(a,b);
int n = a * b / m;
System.out.println("最大公约数: " + m);
System.out.println("最小公倍数: " + n);

}
class deff{
public int deff(int x, int y) {
int t;
if(x < y) {
t = x;
x = y;
y = t;
}
while(y != 0) {
if(x == y) return x;
else {
int k = x % y;
x = y;
y = k;
}
}
return x;
}

------解决方案--------------------
参考一下这个
Java code

package test;

/**
 * 求两个数的最大公约数
 * @author xqh
 *
 */
public class BigCommonNumber {
    public static void main(String[] args) {
        int a = 100; // 第一个数
        int b = 15; // 第二个数
        System.out.println(f(a, b));
    }    
    /**
     * 求两个数的最大公约数 
     * 辗转法
     * @param i 第一个数
     * @param j 第二个数
     * @return 最大公约数
     */
    public static int f(int i, int j){
        return j == 0 ? i : f(j, i % j);
    }
}