GCD(最大公约数) 与 LCM(最小公倍数)

最大公约数与最小公倍数,两个常用的数,由于最小公倍数 = 两数相乘 / 最大公约数,因此我们可以先求最大公约数。

求最大公约数我们可以用,辗转相除法,我还看到一个辗转相减法......

辗转,辗转,就是不断的用一个去除另一个或者不断地用一个去减另一个,直到两者相等。

其计算原理依赖于下面的定理:

定理:两个整数的最大公约数等于其中较小的那个数和两数相除余数的最大公约数。最大公约数(Greatest Common Divisor)缩写为GCD。

gcd(a,b) = gcd(b,a mod b) (不妨设a>b 且r=a mod b ,r不为0)

先相除

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

int GCD(int x, int y)
{
	if(x % y == 0)
		return y;
	else
		return GCD(y, x % y);
}

int main()
{
	int a, b;
	while(~scanf("%d%d", &a, &b))
	{
		int ans = GCD(a, b);
		printf("%d\n", ans);
	}
	return 0;
}

在相减

#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

int GCD(int x, int y)
{
	if(x == y)
		return x;
	else if(x < y)
		return GCD(x, y - x);
	else
		return GCD(x - y, y);
}

int main()
{
	int a, b;
	while(~scanf("%d %d", &a, &b))
	{
		int ans = GCD(a, b);
		printf("%d\n", ans);
	}
	return 0;
}

两种写法并没有什么太大的区别,都是不断地用一个取余另一个数,再将另一个数与余数进行同样的操作,直到余数为零为止。不过在除法中注意返回的是较小的那个数。

现在,求一下最小公倍数。我们只需要做一个小小的修改就可以了

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

int GCD(int x, int y)
{
	if(x % y == 0)
		return y;
	else
		return GCD(y, x % y);
}

int main()
{
	int a, b;
	while(~scanf("%d%d", &a, &b))
	{
		int ans = a * b / GCD(a, b);
		printf("%d\n", ans);
	}
	return 0;
}

就是在答案上做一个简单计算就好

猜你喜欢

转载自blog.csdn.net/someone_and_anyone/article/details/81109788