一. 先介绍2个正整数,求最小公倍数,最大公约数
import java.util.Scanner;
/**
* 求两个数的 最大公约数, 最小公倍数, 通过短除法
*/
public class GongyueAndGongBei {
static int a, b;
public static void main(String[] args) {
input();
jishuan();
}
static void input(){
System.out.println("请输入第一个数:");
a = new Scanner(System.in).nextInt();
System.out.println("请输入第二个数:");
b= new Scanner(System.in).nextInt();
}
static void jishuan(){
int max; //定义最大公约数
int min; //定义最小公倍数
if(a>b){
max = a;
min =b;
}else{
max = b;
min = a;
}
//求得余数
int yushu = max % min; //例如 20, 15, 求余为5
while (yushu != 0){
max = min; //将15赋值为最大数
min = yushu; //将余数赋给最小值, 此时最大数为15, 最小数为5
yushu = max%min; //此时将15%5 取余, 得0
}
System.out.println("最小公倍数为: " + a*b/min);
System.out.println("最大公约数为: " + min + "\n");
input();
}
}
运行结果:
二. 接着,介绍3个正整数求最小公倍数,最大公约数
import java.util.Scanner;
/**
* 求3个正整数的最大公约数, 最小公倍数
*/
public class ThreInt_GongyueAndGongbei {
private static int x, x_init;
private static int y, y_init;
private static int z, z_init;
public static void main(String[] arrgs) {
meun();
}
public static void meun() {
Scanner scanner = new Scanner(System.in);
System.out.println("请选择求最大公约数的算法序号:1.穷举法;2.欧几里得算法;3.辗转相减法");
int or = scanner.nextInt();
if (or < 1 || or > 3) {
System.out.println("没有该选项\n");
meun();
}
System.out.println("请选择求最小公倍数的算法序号:1.欧几里得算法;2.穷举法");
int or2 = scanner.nextInt();
if (or2 < 1 || or2 > 2) {
System.out.println("没有该选项\n");
meun();
}
if (or == 1) {
addNum();
jisuan1();
} else if (or == 2) {
addNum();
jisuan2();
} else if (or == 3) {
addNum();
int bigDiv = getBigDiv(x, y);
int bigDiv1 = getBigDiv(bigDiv, z);
System.out.println("最大公约数为:" + bigDiv1);
}
if (or2 == 1) {
int smallMul = getSmallMul(x_init, y_init);
int smallMul1 = getSmallMul(smallMul, z_init);
System.out.println("最小公倍数为" + smallMul1);
meun();
} else if (or2 == 2) {
int max = x_init > y_init ? x_init : y_init;
max = max > z_init ? max : z_init;
for (; ; max++) {
if (max % x_init == 0 && max % y_init == 0 && max % z_init == 0) {
System.out.println("最小公倍数为" + max);
meun();
}
}
}
}
public static void addNum() {
System.out.println("请输入要求的3个数");
Scanner scanner = new Scanner(System.in);
x = scanner.nextInt();
y = scanner.nextInt();
z = scanner.nextInt();
x_init = x;
y_init = y;
z_init = z;
}
public static int getSmallMul(int a, int b) {// 求两个数的最小公倍数
return (a * b) / getBigDiv(a, b);
}
public static int getBigDiv(int a, int b) {// 求两个数的最大公约数
if (b == 0)
return a;
return getBigDiv(b, a % b);
}
public static void jisuan1() {
int j = 1;
for (int i = 1; i <= x && i <= y && i <= z; i++) {
if (x % i == 0 && y % i == 0 && z % i == 0) {
j = i;
}
}
System.out.print("这三个数的最大公约数为:" + j + " ");
}
public static void jisuan2() {
int j = 0;
while (y != 0) {
j = x % y;
x = y;
y = j;
}
j = 0;
while (z != 0) {
j = x % z;
x = z;
z = j;
}
System.out.print("这三个数的最大公约数为:" + x + " ");
}
}
运行结果: