注册 登录
编程论坛 C++教室

求多个数的最小公倍数

狂人老大 发布于 2007-11-02 22:59, 1258 次点击

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



我的写的程序代码是:
#include <iostream>
using namespace std;
int gcd(int,int);
int lcm(int,int);
int main()
{
int n,k;
while(cin>>k)
for(int m=0;m<k,cin>>n;m++)
{
int m[100]={0};
int LCM;
for(int i=0;i<n;i++)
cin>>m[i];
if(n==1)
LCM=m[0];
else
{
LCM=lcm(m[0],m[1]);
for(int j=2;j<n;j++)
LCM=lcm(LCM,m[j]);
}
cout<<LCM<<endl;
}
return 0;
}
int gcd(int m,int n)
{
if(m%n==0)
return n;
else
return gcd(n,m%n);
}
int lcm(int a,int b)
{
return (a*b)/gcd(a,b);
}


这个程序就是通不过,各位看看,给点意见

6 回复
#2
雨中飞燕2007-11-02 23:17
很简单的溢出



by 雨中飞燕 C/C++学习讨论群:46520219
[url=http://yzfy.org/]C/C++算法习题(OnlineJudge)论坛:[/url] http://yzfy.programfan.com

[url=http://bbs.bc-cn.net/viewthread.php?tid=163571]请大家不要用TC来学习C语言,点击此处查看原因[/url] [url=http://blog.programfan.com/article.asp?id=24801]请不要写出非int声明的main函数[/url]
[url=http://bbs.bc-cn.net/viewthread.php?tid=181314" target="_blank">https://yzfy.org/
Blog: http://yzfy.programfan.com

[url=http://bbs.bc-cn.net/viewthread.php?tid=163571]请大家不要用TC来学习C语言,点击此处查看原因[/url] [url=http://blog.programfan.com/article.asp?id=24801]请不要写出非int声明的main函数[/url]
[url=http://bbs.bc-cn.net/viewthread.php?tid=181314
]C++编写的Windows界面游戏[/url]
#3
狂人老大2007-11-02 23:23
那应该怎样改呢?
想了好久不知道啊
#4
leeco2007-11-02 23:44

题目有说个数<100吗?你为什么自说自话定义int m[100]={0};
另外,虽然题目说All results will lie in the range of a 32-bit integer.
return (a*b)/gcd(a,b);这句仍然是危险的。小朋友还是要积累经验啊

#5
狂人老大2007-11-03 18:03
我自己也不知道把这个int m[100]={0};中的100定义多大
还有就是return (a*b)/gcd(a,b);这句危险在哪呢?指教下
#6
狂人老大2007-11-03 20:48
大家救救我吧    这个程序怎样才能不溢出呢
#7
aipb20072007-11-03 20:58
以下是引用狂人老大在2007-11-3 18:03:34的发言:
我自己也不知道把这个int m[100]={0};中的100定义多大
还有就是return (a*b)/gcd(a,b);这句危险在哪呢?指教下

没说就定义最大可能数

a*b会溢出,因为只保证到a,b分别为32bit

1