问题描述
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
求两个数最小公倍数算法:
最小公倍数=两数的乘积/最大公约数
求两数的最大公约数的算法:
(1)辗转相除法
有两个整数a和b,假设a>=b
1. c=a%b
2. 若c=0,则b就是所求的最大公约数
3. 若c≠0,则a=b,b=c,再回去执行1
(2)相减法
有两整数a和b:
1. 若a>b,则 a=a-b;
2. 若b>a,则 b=b-a;
3. 若a=b,则a(或b)即为两数的最大公约数
4. 若a≠b ,则返回执行1
主要算法
我们已经知道了求两位数的最小公倍数的算法,那么多位数呢?很简单,使最小公倍数初值为1,然后依次与ni求最小公约数。(也就是依次两两求最小公约数)
LCM=1
for i=1 to m
LCM=LCM 和ni的最小公倍数
AC代码
#include<stdio.h>
int getLCM(int a,int b);
int main()
{
int N;
scanf("%d",&N);
while(N--)
{
int m,LCM=1,i,num;
scanf("%d",&m);
for(i=1;i<=m;i++)
{
scanf("%d",&num);
LCM=getLCM(LCM,num);
}
printf("%d\n",LCM);
}
return 0;
}
//求a和b的最小公倍数=A*B/A和B的最大公约数
int getLCM(int a,int b)
{
int t,r,a1=a,b1=b;
//辗转相除法求最大公约数
if(a<b)
{t=a;a=b;b=t;}
do{
r=a%b;
a=b;
b=r;
}while(r>0);
return a1/a*b1;//不要写成a1*b1/a,因为中间结果a1*b1可能不止32位,会溢出。
}