/*
题目:输入两个正整数m和n,求其最大公约数和最小公倍数。
思路:
A:最大公约数maxNum,最小公倍数minNum
B:如果 m=n,则maxNum =minNum = m
C:m<>n,则令m取较大值,n取较小值。
当 m%n == 0 maxNum =n,minNum = m
当 m%n != 0
从n到1进行循环求余,遇到能够求余的就结束,此时maxNum 求得
minNum = m*n/maxNum
*/
import java.util.Scanner;
class NumberDemo
{
public static void main(String [] args)
{
//创建扫描器
Scanner scanner = new Scanner(System.in);
System.out.println("请输入两个数,中间用空格隔开");
int m = scanner.nextInt();
int n = scanner.nextInt();
printNum(m,n);
}
public static void printNum(int m,int n)
{
int maxNum = 0;
int minNum = 0;
if(m == n) // m,n相等的情况
{
maxNum = m;
minNum = n;
}else { // m, n 不相等的情况
if(m < n) // 让m取较大的值,n取较小的值
{
int temp = m;
m = n;
n = temp;
}
if(m % n == 0) // m正好能整除n
{
maxNum = n ;
minNum = m;
}else //m无法整除n
{
for(int i = n;i > 0;i --)
{
if(m % i == 0 && n % i == 0)
{
maxNum = i;
minNum = m * n / maxNum;
break;
}
}
}
}
System.out.println("最大公约数maxNum=" + maxNum +"\n" + "最小公倍数minNum="+ minNum);
}
}
|
|