To find the greatest common divisor of two positive integers and the least common multiple

You are such a problem, still thinking?
Come take a look!
Title: Enter two positive integers m and n, and seeking the least common multiple of the greatest common divisor.
method one:

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
	int m, n, y=0, i, j, z; 
	int x[1000];	
	
	scanf("%d %d",&m,&n);
	
	if (m < n) 
		z = m;						//得到较小的数 
	if (m > n)
		z = n;	
	
	for (i = 2; i <=z; i++){		//找到公约数,并放入整数型数组中 
		if ((m % i) == 0 && (n % i) == 0)
			x[i-2] = i;	
		else 
				x[i-2]=0;				//数组内部不能跳跃空白元素。 
	}
	
	for (j = 0; j < z-1; j++){	
		if (y < x[j])				//找到数组中最大的数 ,即最大公约数 
			y = x[j];
	}
	printf("最大公约数:%d\n", y);				//得到最大公约数 	
	printf("最小公倍数:%d\n",(m * n)/ y);		//最小公倍数 = 原来两个正整数之积除以它们的最大公约数 

	return 0;
}

Briefly outline my ideas:
find an array of integers when the common factor of two numbers and placed among the greatest common divisor obtained by finding the maximum number of array. And thus solve the least common multiple (equal to the original product of two numbers divided by the greatest common divisor)
I had some problems at the time of writing the program, finalized in the continuous help and debugging, and there are about a few benefits:

  1. When declaring an array, to determine the specific length of the array. When exceptions within the array element is initialized, the computer automatically formed at this time of the array.
  2. Internal orderly array elements, elements can not jump into the blank. At this point in the cycle required particular attention, there is one additional solution, when the element is empty, it may be set to 0, i.e., the use of if ... else ... statement.
  3. In the latter part of the continuous process of debugging, the need to mobilize the results. Deviation result output remains at a logic flow is correct, try to mobilize some minor factors, such as the conditions for defining the loop, <= difference between <a.

Method Two:

#include<stdio.h>
int main()
{
    int a,b,t,r;
    printf("请输入两个数字:\n");
    scanf("%d %d",&a,&b);
    if(a<b)
    {t=b;b=a;a=t;}
    r=a%b;
    int n=a*b;
    while(r!=0)
    {
        a=b;
        b=r;
        r=a%b;
    }
    printf("这两个数的最大公约数是%d,最小公倍数是%d\n",b,n/b);
    
    return 0;
}

It concluded that learning is a long journey, you need to go step by step themselves, to understand, of course, the road and have someone for help is a better thing for us, I hope all the joy of learning, etc. are on your side!

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/87911273