问题
编写一个程序,输入m和n两个整数,计算并输出m与n的绝对值的最大公约数及最小公倍数。
分析
这里有2种求法:
-
不知道公约数和公倍数怎么求,只知道最大公约数是最大的共同因子,最大公倍数是最小的公共倍数(这个都不知道那就GG)。
提供的思路:先找出m和n所有的因子然后找出m和n相等的因子(公因子),最后找到其中最大因子,公倍数类似。 -
利用最大公因数和最小公倍数的的算法。
辗转相除法计算最大公因数:1997 % 615 = 152
615 % 152 = 7
152 % 7 = 5
7 % 5 = 2
5 % 2 = 1
2 % 1 = 0至此,最大公约数为1
最小公倍数计算: 两个数的乘积等于这两个数的最大公约数与最小公倍数的积
Java实现
使用算法实现
public static void gcdLcm(){
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
//绝对值
if(n < 0 ) n = -n;
if(m < 0) m = -m;
int a = m;
int b = n;
int r = m % n;
//最大公因数
while(n != 0 && m != 0 && r != 0 ) {
m = n;
n = r;
r = m % n;
}
System.out.println("最大公约数:"+n);
System.out.println("最小公倍数:"+a*b/n);
}
- 时间复杂度:O(n)
- 空间复杂度:O(1)
这种使用思路1实现的小白写法,绝对是复杂明了。
public static void find(){
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int n = scanner.nextInt();
//取绝对值
if (m < 0) m = -m;
if (n < 0) n = -n;
int count1 = 0,count2 = 0,a = 0,b = 0;
//m,n的公因数和公倍数存放的数组
int[] array1 = new int[1000];
int[] array2 = new int[1000];
int[] array3 = new int[1000];
int[] array4 = new int[1000];
//1.判断m和n的大小及是否是公倍数关系
if(m < n) {
int swap = n ;
n = m ;
m = swap ;
}
if(m%n==0){
System.out.println("最大公约数为"+n+"最小公倍数为"+m);
}else {
//2,求m,n的所有因数
for(int i=1 ; i<=m ; i++) {
if(m%i == 0) {
array1[count1]= m/i;
count1++;
}
}
for(int i=1;i<=n;i++) {
if(n%i==0) {
array2[count2] = n/i;
count2++;
}
}
//3.找出相等的公约数
for(int i=0; i<count1 ; i++) {
for(int j=0; j<count2; j++) {
if(array1[i] == array2[j]) {
array3[a] = array1[i];
a++;
}
}
}
//4.输出最大的公约数
System.out.println(m+"和"+n+"的最大公约数为"+array3[0]);
//5.求m,n的所有倍数
for(int i = m+1; i <=m*n; i++) {
if(i%m == 0 && i%n == 0) {
array4[b] = i;
b++;
}
}
System.out.println(m+"和"+n+"的最小公倍数为"+array4[0]);
}
}