3 ways to find the least common multiple (C language)

What is the least common multiple? It refers to the smallest positive integer that can divide a and b at the same time. For example, the common multiples of 3 and 7 are 21, 42, 84, etc. 21 is the lowest common multiple.

Here are three methods to find the least common multiple.

1. Euclidean division: the least common multiple of a and b = a*b/(the greatest common divisor of a and b)

#include <stdio.h>
int main()
{
	int m = 0;
	int n = 0;
	int a = 0;
	scanf("%d %d",&m,&n);
	int x = m * n;
	while (a = m % n)//求两个数的最大公约数
	{
		m = n;
		n = a;
	}
	printf("%d\n",x/n);	
	return 0;
}

 2. The least common multiple of a and b. Take any number, such as a, and find the multiples of a from small to large. There must be multiples of b among them. The smallest one is the least common multiple of a and b (take out bSimilarly)

#include <stdio.h>
int main()
{
	int m = 0;
	int n = 0;
	scanf("%d %d",&m,&n);
	int i = 1;
	while (m * i % n != 0)
	{
		i++;
	}
	printf("%d\n",i*m);
	return 0;
}

 3. (The most clumsy method) Find the largest one between a and b, assign it to m, and then m increases by 1. If a certain m can divide both a and b for the first time, then this m is Least common multiple.

#include<stdio.h>
int main()
{
	int a = 0;
	int b = 0;
	scanf("%d %d",&a,&b);
	int m = a > b ? a : b;//找出a和b的最大值
	while (1)
	{
		if ((m % a == 0) && (m % b == 0))
		{
			break;
		}
		m++;
	}
	printf("%d\n",m);
	return 0;
}

 Among the above three methods, methods 1 and 2 are better, while method 3 is inefficient because it needs to be searched one by one.

Coding is not easy. If you are satisfied with it, please support it with one click and three times~

Guess you like

Origin blog.csdn.net/qq_48460693/article/details/132110412