1662 - Least Common Multiple

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 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.

题目输出

For each problem instance, output a single line containing the corresponding LCM. All results will lie in the range of a 32-bit integer.

输入/输出样例

题目输入

2
2 3 5
3 4 6 12

题目输出

15
12

C语言解答

#include<stdio.h>
int gcd(int m,int n)
{
	if(m%n)
		return gcd(n,m%n);
	return n;
}
int main()
{
	int n,gbs,t,a;
	scanf("%d",&n);
	while(n--)
	{
		gbs=1;
		scanf("%d",&t);
		while(t--)
		{
			scanf("%d",&a);
			gbs=gbs*(a/gcd(gbs,a));
		}
		printf("%d\n",gbs);
	}
}

C++解答

#include<stdio.h>

long long gcd(long long x,long long y)
{
	if(!x||!y)
		return x>y?x:y;
	for(long long t;t=x%y;x=y,y=t);
	return y;
}

int main()
{
	int n,m;
	long long a,b,g,l;
	scanf("%d",&n);
	while(n--)
	{
		scanf("%d%lld",&m,&a);
		if(m==1)
		{
			printf("%lld\n",a);
			continue;
		}
		scanf("%lld",&b);
		g=gcd(a,b);
		l=a*b/g;
		m-=2;
		while(m--)
		{
			scanf("%lld",&a);
			g=gcd(a,l);
			l=a*l/g;
		}
		printf("%lld\n",l);
	}
	return 0;
}
时间限制 1 秒
内存限制 32 MB
讨论 统计
上一题 下一题