最大公约数、最小公倍数

辗转相除法求最大公倍数

1.两个数的最大公倍数(辗转相除法)

#include <iostream>
#include <vector>
#include <set>
using namespace std;

//辗转相除法求两数的最大公约数
int get_Common_divisor(int a, int b)
{
	int divisor = 1;
	if (a < b)
		std::swap(a, b);
	while (divisor != 0)
	{
		divisor = a%b;
		a = b;
		b = divisor;
	}
	return a;
}
int main()
{
	int a, b;
	cin >> a >> b;
	printf("%d和%d的最大公约数是%d\n",a,b,get_Common_divisor(a,b));
	return 0;
}

2.求1-x所有数的最小公倍数

算法思路:

首先求出前x-1个数的最小公倍数,然后和x一起求最小公倍数。

两个数的最小公倍数 = 两数之积/最大公约数。

#include <iostream>
#include <vector>
#include <set>
using namespace std;

//辗转相除法求两数的最大公约数
int get_Common_divisor(int a, int b)
{
	int divisor = 1;
	if (a < b)
		std::swap(a, b);
	while (divisor != 0)
	{
		divisor = a%b;
		a = b;
		b = divisor;
	}
	return a;
}

//求最小公倍数
int get_Common_multiple(int x)
{
	if (x <= 0)
	{
		cout<<"error:除数为0"<<endl;
		exit(1);
	}
	if (x == 1)
		return 1;
	int * vals = new int[x];
	int Common_divisor = 1;
	int tmp = 0;
	vals[0] = 1;
	for (int i = 1; i < x; ++i)
	{
		tmp = i+1;
		Common_divisor = get_Common_divisor(tmp, vals[i - 1]);
		vals[i] = tmp / Common_divisor * vals[i - 1];
	}
	return vals[x - 1];

}
int main()
{
	int a;
	while (cin)
	{
		cin >> a;
		printf("1-%d的最小公倍数是%d\n", a, get_Common_multiple(a));
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值