Find the greatest common divisor and least common multiple of two numbers

content

greatest common divisor

The solution of violence

Two, tossing and dividing method

Least common multiple

The solution of violence

Two, tossing and dividing method


greatest common divisor

The solution of violence

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>

int main()
{
	int num1 = 0;
	int num2 = 0;
	scanf("%d%d", &num1, &num2);
	int min = (num1 < num2 ? num1 : num2);
	while (1)
	{
		if (num1 % min == 0 && num2 % min == 0)
		{
			break;
		}
		min--;
	}
	printf("最大公约数:%d\n", min);
	return 0;
}

Two, tossing and dividing method

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>

int main()
{
	int num1 = 0;
	int num2 = 0;
	scanf("%d%d", &num1, &num2);
	int k = 0;
	while (k = num1 % num2)
	{
		num1 = num2;
		num2 = k;
	}
	printf("最大公约数:%d\n", num2);
	return 0;
}

Least common multiple

The solution of violence

int main()
{
	int num1 = 0;
	int num2 = 0;
	scanf("%d%d", &num1, &num2);
	int max = num1 > num2 ? num1 : num2;
	int i = 0;
	for (i = max;; i++)
	{
		if (i % num1 == 0 && i % num2 == 0)
			break;
	}
	printf("最小公倍数:%d\n", i);

	return 0;
}

Two, tossing and dividing method

First, find the greatest common divisor using the method of rolling division , and then divide the product of the two numbers by the greatest common divisor to obtain the least common multiple.

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>

int main()
{
	int num1 = 0;
	int num2 = 0;
	scanf("%d%d", &num1, &num2);
	int m = num1;
	int n = num2;

	int k = 0;
	while (k = num1 % num2)
	{
		num1 = num2;
		num2 = k;
	}
	printf("最小公倍数:%d\n", m * n / num2);
	return 0;
}

Note : Two numbers a, b, the greatest common divisor and the least common multiple are m and n, then a*b=m*n. 

Guess you like

Origin blog.csdn.net/qq_54880517/article/details/123192367