方法一:很好理解但是耗费内存
import java.util.Scanner;
public class yueBei {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("请输入两个不为0的整数小的在前大的在后");
int n1 = sc.nextInt();
int n2 = sc.nextInt();
for (int i = n1; i > 0; i--) {
if(n2%i==0&&n1%i==0) {
System.out.println("最大公约数为"+i);
break;
}
}
for (int i = 1; i <=n2; i++) {
for (int j = 1; j <= n1; j++) {
if(i*n1==j*n2) {
System.out.println("最小公倍数为"+i*n1);
return;
}
}
}
}
}
方法二:辗转相除并且利用公式,节省内存。
import java.util.Scanner;
public class yueBei2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("请输入两个不为0的整数小的在前大的在后");
int n1 = sc.nextInt();
int n2 = sc.nextInt();
int temp = 0;
int x = n1*n2;
while (n1 != 0) {
temp = n2 % n1;
n2 = n1;
n1 = temp;
}
int a = n2;
System.out.println("最大公约数:"+a);
//根据公式最小公倍数等于两者乘积除以最大公约数
int b = x/a;
//一定要提前定义好乘积
System.out.println("最小公倍数"+b);
}
}