java题目:输入两个正整数m和n求其最大公约数和最小公倍数。程序分析:1最小公倍数=输入的两个数之积除于它们的最大公约数关键是求出最大公约数;2求最大公约数用辗转相除法又名欧几里德算法1证明:设c是a和b的最大公约数记为c=gcdaba=b令r=a mod b设a=kcb=jc则kj互素否则c不是最大公约数据上r=a-mb=kc-mjc=k-mjc可知r也是c的倍数且k-mj与j互素否则与前述k
import java.util.Scanner;
public class GcdLcm {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first positive integer: ");
int m = scanner.nextInt();
System.out.print("Enter the second positive integer: ");
int n = scanner.nextInt();
int gcd = findGCD(m, n);
int lcm = m * n / gcd;
System.out.println("The greatest common divisor is: " + gcd);
System.out.println("The least common multiple is: " + lcm);
}
public static int findGCD(int a, int b) {
if (b == 0) {
return a;
}
return findGCD(b, a % b);
}
}
注意:这里使用了递归来实现辗转相除法求最大公约数。
原文地址: https://www.cveoy.top/t/topic/i4Kt 著作权归作者所有。请勿转载和采集!