Least Common Multiple(欧几里得算法:也叫辗转相除法)

原题点击获取~~~

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

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

Source

East Central North America 2003, Practice

Recommend

JGShining

问题简述:
第一行依旧是输入例子数,第二行的第一个数字表示要计算的是那些数,这个数字是多少,后面就要输入多少位数。

个人感想:
我只想说…ACM周赛一眼看到这题还以为很难…然后直接跳过了…没想到原来蛮简单…
回归正题:别被欧几里得算法给吓到,它另一个名字就叫做辗转相除法,相信读过高中的童鞋们应该都通过这个,再者,其实就求最大公倍数!!!!是不是就觉得很简单了,更离谱的是,两位数的最大公倍数对于者两个数相乘的结果除于最小公约数!!这样就转化为求最小公约数了,我的C++课本里就有这个求法,所以只要弄个求最小公约数的函数就行了。

AJ通过的代码如下:

#include <iostream>
using namespace std;
long long gcd(long long a, long long b)
{
	int g;
	if (b == 0) g = a;
	else g = gcd(b, a%b);
	return g;
}
long long lcm(long long a, long long b)
{
	int g;
	g = (a / gcd(a, b))*b;
	return g;
}
int main()
{
	int T;
	cin >> T;
	while(T--)
	{
		int n[1000];
		int k;
		cin >> k;
		int d = 1;
		for (int i = 1;i <= k;i++)
		{
			scanf_s("%d", &n[i]);
			d = lcm(d, n[i]);
		}
		printf("%d\n", d);
	}
}

Status:
Accepted
Time:
15ms
Memory:
1792kB
Length:
438
Lang:
C++
Submitted:
2018-12-21 16:54:21

猜你喜欢

转载自blog.csdn.net/weixin_43697280/article/details/85176978