一、热身 [Cloned] I - 辗转相除法求最大公约数

本文介绍了一种使用辗转相除法求解一组正整数的最小公倍数的算法。通过先求两个数的最大公约数,再利用此结果求最小公倍数,最后逐步扩展到整个数列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题:

The least common multiple (LCM) of a set of positive integers is the smallest positive integer which is divisible by all the numbers in the set. For example, the LCM of 5, 7 and 15 is 105. 

题意:

给出一串数字,求出他们的最小公倍数

题解:

辗转相除法求a与b的最大公约数是指,a%b=q......r1,然后再用b%r1,直到的到余数为0,则最大公约数就是被除数,而要求a,b的最小公倍数,就是讲a*b/最大公约数。用一个函数来求前两个数的最小公倍数,然后依次与后一个数字求最小公倍数,最后得到整个数列的最小公倍数。

代码:AC

#include<iostream>
using namespace std;
long long lcm(long long a,long long b)
{
	long long loss,a1,b1;
	a1=a;
	b1=b;
	while(b>0)
	{
		loss=a%b;
		a=b;
		b=loss;
	}
	return (a1*b1)/a;
}
int main()
{
	long long n;
	cin>>n;
	while(n)
	{
		long long m;
		long long a,b,c;
		cin>>m;
		if(m==1)
		{
			cin>>c;
			cout<<c<<endl;
		}
		else
		{
			cin>>c;
			cin>>b;
			c=lcm(c,b);
			m-=2;
			while(m)
			{
				cin>>b;
				c=lcm(b,c);
				m--;
			}
			cout<<c<<endl;
		}
		n--;
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值