您的位置:首页 > 其它

最大公约数和最小公倍数

2013-03-16 15:02 246 查看
题目:输入两个正整数m和n,求其最大公约数和最小公倍数。
在循环中,只要除数不等于0,用较大数除以较小的数,
将小的一个数作为下一轮循环的大数,
取得的余数作为下一轮循环的较小的数,
如此循环直到较小的数的值为0,返回较大的数,此数即为最大公约数,
最小公倍数为两数之积除以最大公约数

import java.util.*;
public class Test{
//求最大公约数
public int cal(int a,int b){
//使得a>=b
if(a<b){
int f = a;
a=b;
b=f;
}
while(b!=0){
if(a==b) return a;
else{
int k = a%b;
a=b;
b=k;
}
}
return a;
}
//求的两个数的最大公约数
public int cal2(int a,int b){
return a*b/cal(a,b);
}
public static void main(String args[]){
int a,b,m,n;
Scanner s = new Scanner(System.in);
System.out.println("please input a integer: ");
a = s.nextInt();
System.out.println("pleanse input another integer: ");
b = s.nextInt();
m = new Test().cal(a,b);
n = new Test().cal2(a,b);
System.out.println("result is: "+m);
System.out.println("result2 is: "+n);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: