码迷,mamicode.com
首页 > 其他好文 > 详细

题目1439:Least Common Multiple(求m个正数的最小公倍数lcm)

时间:2017-04-10 23:12:37      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:amp   blank   iostream   overflow   ios   algorithm   main   color   nbsp   

题目链接:http://ac.jobdu.com/problem.php?pid=1439

 

详解链接:https://github.com/zpfbuaa/JobduInCPlusPlus

 

参考代码:

//
//  1439 Least Common Multiple.cpp
//  Jobdu
//
//  Created by PengFei_Zheng on 10/04/2017.
//  Copyright © 2017 PengFei_Zheng. All rights reserved.
//

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <cmath>

using namespace std;
//to avoid overflow thus use long long to store data
long long  gcd(long long a, long long b){
    return b==0 ? a : gcd(b,a%b);
}

long long lcm(long long a, long long b){
    return (a/gcd(a,b))*b;// not a*b/gcd(a,b) beacuse it may cause overflow
}

int main(){
    int kase;
    scanf("%d",&kase);//kase number
    while(kase--){//a small tips
        int m;
        scanf("%d",&m);
        long long  ans;
        scanf("%lld",&ans);// input the first number
        for(int i = 1 ; i < m ; i++){
            long long tmp;//to store the next number
            scanf("%lld",&tmp);
            ans = lcm(ans,tmp);//calculate each two adjacent elements‘s lcm
        }
        printf("%lld\n",ans);//print the answer
    }
    return 0;
}

 

题目1439:Least Common Multiple(求m个正数的最小公倍数lcm)

标签:amp   blank   iostream   overflow   ios   algorithm   main   color   nbsp   

原文地址:http://www.cnblogs.com/zpfbuaa/p/6691393.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!