import java.lang.Math;
import java.util.Scanner;
class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
maxPact(sc);
minTimes(sc);
}
//异常判断
public static int exception(Scanner sc) {
int a;
try {
a = sc.nextInt();
}
catch (Exception ex) {
return -1;
}
return a;
}
//最大公约数
public static void maxPact(Scanner sc) {
int a = 0,b = 0,key = 0;
System.out.println("请输入两个正整数:");
a = exception(sc);
if(a == -1) {
System.out.println("数据类型输入错误!");
return;
}
b = exception(sc);
if(b == -1) {
System.out.println("数据类型输入错误!");
return;
}
for (int i = 1;i <= (a < b? a : b);i++) {
if(a % i == 0 && b % i == 0) {
key = i;
}else {
continue;
}
}
if (key != 0) {
System.out.println(a + "和" + b + "的最大公约数是: " + key);
}else {
System.out.println(a + "和" + b + "没有公约数!");
}
}
//最小公倍数
public static void minTimes(Scanner sc) {
int a = 0,b = 0,key = 0;
System.out.println("请输入两个正整数:");
a = exception(sc);
if(a == -1) {
System.out.println("数据类型输入错误!");
return;
}
b = exception(sc);
if(b == -1) {
System.out.println("数据类型输入错误!");
return;
}
for (int i = a * b; i >= (a > b? a : b);i-- ) {
if(i % a == 0 && i % b == 0) {
key = i;
}else {
continue;
}
}
if (key != 0) {
System.out.println(a + "和" + b + "的最小公倍数是:" + key);
}else {
System.out.println(a + "和" + b + "没有最小公倍数!");
}
}
}
|
|