java求最小公倍数和最大公约数

程序填空,不要改变与输入输出有关的语句。
输入一个正整数 repeat (0<repeat<10),做 repeat 次下列运算:
输入两个正整数m和n,输出它们的最小公倍数和最大公约数。
输入输出示例:括号内为说明
输入:
3 (repeat=3)
3 7 (m=3,n=7)
24 4 (m=24,n=4)
24 18 (m=24,n=18)
输出:
the least common multiple:21, the greatest common divisor:1
the least common multiple:24, the greatest common divisor:4
the least common multiple:72, the greatest common divisor:6

我的程序
import java.util.*;

public class Test40014 {
public static void main(String []args){
Scanner in =new Scanner(System.in);
int gcd, lcm, m, n,r;
int repeat, ri;
repeat=in.nextInt();
for(ri = 1; ri <= repeat; ri++){
m=in.nextInt();
n=in.nextInt();

if(m <= 0 || n <= 0)
System.out.println("m <= 0 or n <= 0");
else{
m=m>=n?m:n;
n=m<=n?m:n;
r=m%n;
lcm=m*n;
if (r>n) { gcd=1;}
else{
while(r>0&&r<=n){

m=n;
n=r;
r=m%n;
}
gcd=n;}
lcm=lcm/gcd;
System.out.println("the least common multiple:"+lcm+", the greatest common divisor:"+gcd);
}
}
}
}

可是输入3,7这样互质的数字的时候,就会出问题。我不知道错在那~~急求

/**
* 最大公约数
* 更相减损法:也叫更相减损术
* ??? 第一步:任意给定两个正整数;判断它们是否都是偶数。若是,则用2约简;若不是则执行第二步。
* 第二步:以较大的数减较小的数,接着把所得的差与较小的数比较,并以大数减小数。继续这个操作,直到所得的减数和差相等为止。
* @param a
* @param b
* @return
*/
public static int gongyue( int a, int b){
if(a == b){
return a;
} else{
return gongyue(abs (a-b),min(a,b));
}

}
/**
* 最大公约数
* 辗转相除法:辗转相除法是求两个自然数的最大公约数的一种方法,也叫欧几里德算法.
* 例如,求(319,377):
* ∵ 377÷319=1(余58)
* ∴(377,319)=(319,58);
* ∵ 319÷58=5(余29),
* ∵ 58÷29=2(余0),
* ∴ (58,29)= 29;
* ∴ (319,377)=29.
* @param a
* @param b
* @return
*/
public static int gongyue1( int a, int b){
if(b!=0){
return gongyue1(b,a%b);
} else{
return a;
}
}

/**
* 最小公倍数
* 两个数乘积除去最大公约数即可
* @param a
* @param b
* @return
*/
public static int gongbei( int a, int b){
return a*b/gongyue(a,b);
}

public static int abs(int i){
return i>=0?i:-i;
}
public static int min(int a,int b){
return a<b?a:b;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-04-15
这样不错啊
第2个回答  2014-04-14
r=m%n
输入3,7时,3比7小得不到余数
相似回答