使用辗转相除法,个人觉得这个比较容易理解
假设求2和27的最大公因数和最小公倍数
A 列 B列
2 % 27 = 0 ···2
27 % 2 = 13··1
2 % 1 = 2····0
1 % 0
当B=0时,A就是最大公因数
A列 B列
2 % 10 = 0···2
10 % 2 = 5···0
2 % 0
当B=0时,A就是最大公因数
看到这里大家都应该明白了,把除数换成被除数,余数变成除数,一直循环下去,当B = 0 时,被除数就是最大公因数
最小公倍数就是
A和B乘积/最大公因数 =最小公倍数
我们求这个问题时,要知道最大公因数以及最小公倍数的数学解怎么求,才能去通过代码的方式求出来,不然就没有头绪,废话不多说,上代码
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a =scanner.next();
String b = scanner.next();
int c = test(Integer.parseInt(a),Integer.parseInt(b));
System.out.println("这是最大公因数"+c);
int d = test2(Integer.parseInt(a),Integer.parseInt(b));
System.out.println("这是最小公倍数"+d);
}
// 求最大公因数 使用辗转相除
public static int test(int a,int b){
if(b==0){
return a ;
}
// 余数
int p = a%b;
return test(b,p);
}
// 求最小公倍数
public static int test2(int a,int b){
// 乘积
int he = a*b;
// 最大公因数
int big = test(a,b);
// 乘积/最大公因数 =最小公倍数
int beishu = he/big;
return beishu;
}