H - Least Common Multiple H - 最小公倍数

本文介绍了一种计算一组正整数最小公倍数(LCM)的高效方法,通过逐个与现有LCM计算,降低时间复杂度,适合处理大量数据。C++代码示例展示了如何在输入实例中应用此策略。
摘要由CSDN通过智能技术生成

题目

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.
一组正整数的最小公倍数 (LCM) 是最小的正整数,可以被该集合中的所有数字整除。例如,5、7 和 15 的 LCM 为 105。

 

Input

Input will consist of multiple problem instances. The first line of the input will contain a single integer indicating the number of problem instances. Each instance will consist of a single line of the form m n1 n2 n3 ... nm where m is the number of integers in the set and n1 ... nm are the integers. All integers will be positive and lie within the range of a 32-bit integer.
输入将包含多个问题实例。输入的第一行将包含一个整数,指示问题实例的数量。每个实例将由一行组成,格式为 m n1 n2 n3 ...nm 其中 m 是集合中的整数数,n1 ...nm 是整数。所有整数都是正数,并且位于 32 位整数的范围内。

Output

For each problem instance, output a single line containing the corresponding LCM. All results will lie in the range of a 32-bit integer.
对于每个问题实例,输出包含相应 LCM 的单行。所有结果都将位于 32 位整数的范围内。

Sample

InputcopyOutputcopy
2
3 5 7 15
6 4 10296 936 1287 792 1
105

思路 

如果将所有数都算起来以大数为标准进行寻找,由于数据量的数量众多,同时数据范围很大,放一起进行查找的话很容易出现问题,和上题类似,我们可以采用逐个计算的方法,来减少时间复杂度,具体的代码如以下实现。

代码实现

#include <bits/stdc++.h>
using namespace std;
int lcm(int a,int b){
	return a/__gcd(a,b)*b;//计算最小公倍数
}
int main() {
	std::ios::sync_with_stdio(false);
	std::cin.tie(0);
	std::cout.tie(0);//关闭同步流
	int t;
	cin>>t;
	while(t--){//多实例
		int m,n=1,e;
		cin>>m;//个数
		while(m--){
			cin>>e;
			n=lcm(e,n);//逐个计算,减少时间复杂度
		}
		cout<<n<<endl;//输出
	}
	return 0;
}

总结

本题延续了上题的分开计算,根据输入逐个计算,从而减少一起计算的麻烦和时间复杂度,希望大家能够理解和认识到这种思想,在时间超限的情况下通过该种方法进行简化和实现。

尾声

分立的计算能够把整体的计算化为简单的各部分,从而简化题目的要求与实现,如果觉得作者写的还不错的话,记得留下你的点赞收藏和关注哦~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sinking tenderness

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值