题目:
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
题目意思很简单,就是给你一组序列,让你求出这组序列的最小公倍数。
这道题有两个注意的地方:
- 考虑这个序列中只有一个元素的情况(最小公倍数就是那个数)。
- 当心溢出(用long long)。
参考代码:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
typedef long long ll;
vector<ll> v;
void init() {
v.clear();
}
void input(int n) {
ll num;
for (int i = 0;i < n;++i) {
cin >> num;
v.push_back(num);
}
}
ll gcd(ll a, ll b) {
if (b == 0) return a;
else return gcd(b, a % b);
}
ll lcm(ll a, ll b) {
ll g = gcd(a, b);
ll d = a * b;
return d / g;
}
ll result(int n) {
if (n == 1) return v[0];
ll ans = lcm(v[0], v[1]);
for (string::size_type i = 2;i < v.size();++i) {
ans = lcm(ans, v[i]);
}
return ans;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
init();
input(n);
ll ans = result(n);
cout << ans << endl;
}
return 0;
}