本题链接:点击打开链接
ps:在此以1019题为例,2028和1019题几乎是一样的就不再冗余了。
Least Common Multiple
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 52058 Accepted Submission(s): 19752
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
Recommend
本题题意:还是简单说一下题意吧,先输入一个整数n,代表有n组测试数据,然后输入m,表示该组测试有m个数,求这m个数的最小公倍数。
解题思路一:常规解题,利用最大公约数的方法,两个两个的找最大公约数,再求最小公倍数,因为两个数的最小公倍数=这两个数相乘÷它们的最大公约数,一直求到最后一个就是了。值得注意的是这个题要用__int64 型才给过。
代码一:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int gcd(__int64 a,__int64 b)
{
__int64 t,r,p;
if(a<b) //保证第一个数大于大二个数
{
t=a;
a=b;
b=t;
}
p=a*b;
while(b) //相当于辗转相除求最大公因数
{
r=a%b;
a=b;
b=r;
}
return p/a;
}
int main()
{
int t;
__int64 a[10005];
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
for(int i=0; i<n; i++)
scanf("%I64d",&a[i]);
for(int i=0; i<n; i++)
a[i+1]=gcd(a[i],a[i+1]); //用每两个数的后一个数保存这两个数的最小公倍数
printf("%I64d\n",a[n-1]);
}
return 0;
}
代码一(精简版):
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int gcd(__int64 a,__int64 b) //求最大公因数
{
return b?gcd(b,a%b):a;
}
int main()
{
int t;
__int64 a[10005],p;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
for(int i=0; i<n; i++)
scanf("%I64d",&a[i]);
for(int i=0; i<n; i++)
{
p=a[i]*a[i+1];
a[i+1]=p/gcd(a[i],a[i+1]); //用每两个数的后一个数保存这两个数的最小公倍数
}
printf("%I64d\n",a[n-1]);
}
return 0;
}
解题思路二:(尴尬,这种方法做1019这个题目超时了,这个题目的数据规模大一点吧,但做2028这个题还是0ms)思路是先找到该组测试数据的最大数,然后依次判断该数是否能整除前i个数,不能就一直加一,直到能将n个数都整数为止,这种方法适用于数据规模比较小的情况。下面附此题 Time Limit Exceeded 代码。
代码二:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
__int64 maxx;
__int64 a[10005]; //保险起见,还是开的__int64 的整型,视情况而定吧
scanf("%d%I64d",&n,&a[0]);
maxx=a[0];
for(int i=1;i<n;i++)
{
scanf("%I64d",&a[i]);
if(a[i]>maxx)
maxx=a[i];
}
for(int i=0;i<n;i++)
{
if(maxx%a[i]!=0) //判断该数能否整数a[i],
{
maxx++;
i=0; //不能整数a[i],则需要重新从第一个数开始判断
}
}
printf("%I64d\n",maxx);
}
return 0;
}