C language - find the greatest common divisor and least common multiple of two numbers

Common ways to find the greatest common divisor of two numbers:

※ "Reversing and dividing method", also known as Euclidean algorithm. The basic method is as follows:

Let two numbers be a and b (a>b), divide a by b, get a÷b=q...r, if r=0, then the greatest common divisor is b; if r≠0, Then use b÷r again to get b÷r=q...r', if r'=0, then the greatest common divisor is r', if r'≠0, continue to use r÷r'. .....until it is divisible, at which point the divisor is the greatest common divisor.

For example: a=99, b=18. a÷b=99÷18=5...9 is not divisible, then b÷r=18÷9=2 can be divisible, then the divisor 9 at this time is the greatest common divisor of the two numbers a and b .

① The code is as follows:

#include <stdio.h>
intmain()
{
	int a = 0;
	int b = 0;
	int t = 0;
	scanf("%d%d", &a, &b);//99,18
	while (a%b != 0){
		t = a%b;
		a = b;
		b = t;
	}
	printf("The greatest common divisor is: %d\n", b);
	return 0;
}

First, type the values ​​of two numbers a and b from the keyboard, and the variable t holds the remainder. Use the while loop to judge whether it is divisible or not. According to the "reversing and dividing method", first use the first number a÷b, then assign the divisor b to a, and assign the remainder to b, and the cycle repeats until it can be divisible. End the loop, at this time The divisor b is the greatest common divisor.

(Special note: if a<b, for example a=18, b=99. t=a%b=18; a=99; b=t=18. We found that the values ​​of a and b were exchanged through a loop, which When the condition of a>b can be satisfied, the greatest common divisor can be obtained by continuing to divide according to the method of tossing and turning.)


※Extension: Find the least common multiple of two numbers

Regarding the least common multiple and the greatest common divisor, there is such a theorem: the least common multiple × the greatest common divisor = the product of two numbers.

That is: least common multiple = product of two numbers ÷ greatest common divisor

②The code is as follows:

#include <stdio.h>
intmain()
{
	int a = 0;
	int b = 0;
	int t = 0;
	scanf("%d%d", &a, &b);//18 99
	int m = a;
	int n = b;
	while (a%b != 0){
		t = a%b;//remainder 9
		a = b;//18
		b = t;//9
	}
	printf("The greatest common divisor is: %d\n", b);//9
	printf("The LCM is: %d\n",m*n/b);
	return 0;
}

First, type the values ​​of two numbers a and b from the keyboard, and the variable t holds the remainder. Then set two variables m and n to save the original values ​​of a and b.

First, find the greatest common divisor b' according to the method of rolling and dividing (the process is the same as ①), and then obtain the least common multiple from the least common multiple = the product of the two numbers ÷ the greatest common divisor = m×n÷b'.







Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325818231&siteId=291194637