题目:输入两个正整数m和n,求其最大公约数和最小公倍数。
最大公约数用辗转相除法求得即可,最小公倍数为两数之积除以最大公约数。
代码为:
import java.util.Scanner;
public class zuidagongyueshu {
public static void main(String[] args) {
int a, b, m;
Scanner s = new Scanner(System.in);
System.out.println("请输入一个数:");
a = s.nextInt();
System.out.println("请再输入一个数:");
b = s.nextInt();
deff gongyueshu = new deff();
m = gongyueshu.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 = y;
y = x;
x = t;
}
while (y != 0) {
if (x == y) return x;
else {
int k = x % y;
x = y;
y = k;
}
}
return x;
}
}