//输入两个正整数m和n,求其最大公约数和最小公倍数。
方法一:
public class ZuiDaoGongYueShuYuZuiXiaoGongBeiShu {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("请输入第一个整数m: ");
int m=scanner.nextInt();
System.out.println("请输入第二个整数n: ");
int n=scanner.nextInt();
int max = (m > n) ? m : n;
int min = (m < n) ? m : n;
//最大公约数
for(int i =min;i >= 1;i--){
if( m % i == 0 && n % i ==0){
System.out.println(i);
break;
}
}
//最小公倍数
for(int i = max;i <= m * n;i++){
if(i % m == 0 && i % n == 0){
System.out.println(i);
break;
}
}
}
}
方法二:
/**在循环中,只要除数不等于0,用较大数除以较小的数,将小的一个数作为下一轮循环的大数,取得的余数作为下一轮循环的较小的数,如此循环直到较*小的数的值为0,返回较大的数,此数即为最大公约数,最小公倍数为两数之积除以最大公约数。* /
public class
lianxi06 {
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;
}
}
或者这样写:
class Test{
public static void main(String[] args){
System.out.print("请输入两个正整数:");
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
int b = scan.nextInt();
if(a < b) //确保a是大的数
a = (a + b) - (b = a);
int m = a;
int n = b;
while(a % b != 0){
int iTemp = a;
a = b;
b = iTemp % b;
}
System.out.println(m + "和" + n + "的最大公约数为:" + b);
System.out.println(m + "和" + n + "的最小公倍数为:" + m*n/b);
}
}