在循环中,只要除数不等于0,用较大数除以较小的数,将小的一个数作为下一轮循环的大数,取得的余数作为下一轮循环的较小的数,如此循环直到较小的数的值为0,返回较大的数,此数即为最大公约数,最小公倍数为两数之积除以最大公约数。
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;
}
本文地址:https://blog.csdn.net/weixin_46503529/article/details/107405113
如对本文有疑问, 点击进行留言回复!!
SpringBoot引用阿里easyexcel,Excel导出返回浏览器下载
HashMap、Hashtable、ConcurrentHashMap三者间的异同
解决RecycleView 中Item包含Edittext时,滑动view复用导致数据错乱的问题
多线程、同步工作原理、死锁案例、Lock接口、线程的生命周期的讲解及实现
网友评论