HDU1019 Least Common Multiple c++

Least Common Multiple

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 65257 Accepted Submission(s): 24876

Problem Description
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.

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.

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.

Sample Input
2
3 5 7 15
6 4 10296 936 1287 792 1

Sample Output
105
10296

问题连接

问题描述

求一组数的最小公倍数。

问题分析

设a,b的最小公倍数lcm(a,b)为L,最大公因数gcd(a,b)为g,那么有L=ab/g。
简单的想就是再设a =g
c, b=gd,显然L=cdg=ab/g。(上面的’='都代表等于)
gcd(a,b)的求法很多,递归,或者循环都可以。
由此,这道题就很容易解决了,要求一组数的LCM,就是两个数之间求LCM1,用这个LCM1再与第三个数求LCM2,以此类推,找到最后一个LCM,它就是答案。
注意一下:这题有个坑,题目虽然说保证输入以及输出都能在int型的范围内,但求LCM时先进行相乘有出现溢出的可能,故先进行除,再进行乘,即a/g*b。

c++程序如下

#include<iostream>
using namespace std;
int gcd(int, int);
int lcm(int, int);
#define N 100
int main()
{
	int num[N];
	int i, n, t;
	cin >> t;
	while (t--)
	{
		cin >> n;
		for (i = 0; i < n; i++)
		{
			cin >> num[i];
		}
		for (i = 1; i < n; i++)
			num[i] = lcm(num[i - 1], num[i]);
		cout << num[n - 1] << endl;
	}
	return 0;
}
int gcd(int x, int y)
{
	int t = x;
	while (x)
	{
		t = x;
		x = y%x;
		y = t;
	}
	return y;
}
int lcm(int x, int y)
{
	return x / gcd(x, y)*y;//避免数据溢出,先除后乘
}

ACC

猜你喜欢

转载自blog.csdn.net/DouglasConnor/article/details/85176747