原题地址:http://acm.hdu.edu.cn/showproblem.php?pid=2028已AC。
最小公倍数可用两数之积除以最大公约数求得,本题需注意由于输入数的个数没有限制,两数之积可能超过32位整数,故这里采用先除后乘,这样保证输出的结果为32位整数。
#include<iostream>
using namespace std;
int gcd(int m, int n)
{
int r=1;
while(r != 0)//辗转相除求最大公约数
{
r = m % n;
m = n;
n = r;
}
return m;
}
int lcm(int m, int n)
{
int temp = gcd(m, n), result;
result = m / temp * n;//m*n结果可能越界,所以这里作个转换
return result;
}
int main()
{
int n, m, result;
while(cin >> n)
{
result = 1;
for( int i = 0; i < n; i++)
{
cin >> m;
result = lcm(result, m);
}
cout << result << endl;
}
return 0;
}