九度OJ题目1439-Least Common Multiple

题目描述:
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 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.

输出:
For each problem instance, output a single line containing the corresponding LCM. All results will lie in the range of a 32-bit integer.

样例输入:
2
3 5 7 15
6 4 10296 936 1287 792 1
样例输出:
105
10296
参考代码:

/*m个数的最小公倍数

m个数的最大公约数=m个数的乘积在除以最小公倍数*/

/*
多个数的最小公倍数(注意乘积的范围,要使用大整数!!)
思路是先求两个数的最小公倍数,在和下一个元素进行同样操作,最后得出n个数的最小公倍数
反过来可以求出最大公约数,n个数的乘积除以最小公倍数
而不是正向思路去求最大公约数
*/
#include<cstdio>
#include<cmath>
using namespace std;
#define N 1001
long long buf[N];
long long gcd(long long a, long long b) {
	while (b) {
		int t = a%b;
		a = b;
		b = t;
	}
	return a;
}
long long lcm(long long a, long long b)
{
	//return a*b/gcd(a,b);
	return a / gcd(a, b)*b;//为什么要先除后乘?担心溢出?,最保险的方法是使用高精度整数
}
int main() {
	int n;
	while (scanf("%d", &n) != EOF) {
		int cnt;
		scanf("%d", &cnt);
		for (int i = 0; i < cnt; i++) {
			scanf("%lld", &buf[i]);
		}	
		long long x=buf[0];
		for (int i = 1; i < cnt; i++) {
			x = lcm(x, buf[i]);
		}
		printf("%lld\n", x);
/*long long s = buf[0] * buf[1];
		long long x =s/gcd(buf[0], buf[1]);
		for (int i = 2; i < cnt; i++) {
			s = x*buf[i];
			x = s/gcd(x, buf[i]);
		}*/
	}
	return 0;
}
发布了53 篇原创文章 · 获赞 3 · 访问量 3520

猜你喜欢

转载自blog.csdn.net/sinat_38292108/article/details/88254744