5.一组正整数的最小公倍数

这是一个运用小技巧的题,其实基本方法是可以解决问题的,但是用时比较长,对于较小的,较短的数据可以轻松通过,但是对于后台数据比较大,或者比较多,就需要考虑到运用技巧。

下面我们一起来看一下题目:

 

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

                               (๑•ᴗ•๑)   好吧,英文的,那就看翻译吧:

 

描述

一组正整数的最小公倍数(LCM)是最小正整数,其可被集合中的所有数字整除。例如,5,7和15的LCM是105。 
 

 

输入

输入将包含多个问题实例。输入的第一行将包含一个整数,表示问题实例的数量。每个实例将由m n1 n2 n3 ... nm形式的单行组成,其中m是集合中的整数数,n1 ... nm是整数。所有整数都是正数,并且位于32位整数的范围内。 

 

产量

对于每个问题实例,输出包含相应LCM的单行。所有结果都将位于32位整数的范围内。 

 

样本输入

 

2

3 5 7 15

6 4 10296 936 1287 792 1     

通过观察数据发现,其实数据量是比较大的,那么大家就需要考虑用技巧了。

 

样本输出

 

105

10296

下面是通过的代码:

其实这个思路就是输入每输入一次就求一次最小公倍数,这样再把所有的最小公倍数相乘就可以。

例如:已知a,b。那么我们可以很轻松的求出最小公倍数C,那么最大公约数d就可以这样求:d=a*b/c,也可以通过GCD来求出最大公约数。

以下代码将上述过程反了过来,先GCD求最大公约数,再求最小公倍数~

s=a/gcd(a,b)*b;  代码中的这一行就是核心,这里可能有好多人看不太懂了,因为,为了避免先算乘法的数据量太大,这里先算了除法。

这样大家应该就懂了:s=b*a/gcd(a,b);

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
long long int gcd(long long int a,long long int b)
{
    if(a==0)
    {
        return b;
    }
    else
    {
        return gcd(b % a,a);
    }
}
int main()
{
    long long int s,n,a,b,i,j,m;
    scanf("%lld",&n);
    for(j=1; j<=n; j++)
    {
        scanf("%lld",&m);

        s=0;
        a=1;
        for(i=1; i<=m; i++)
        {
            scanf("%lld",&b);
            s=a/gcd(a,b)*b;
            a=s;
        }
        printf("%lld\n",s);
    }
    return 0;
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值