HDU1019 Least Common Multiple

PS: 如果开始求解 前两个数字的最小公倍数,然后迭代求解下面的则TLE,如果开始求解第一个数字和1的LCM则 0ms.

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

int gcd(int a, int b) {
    if(b==0) return a;
    else return gcd(b, a%b);
}

int main()
{
    int T, n, x;
    int ans;
    scanf("%d", &T);
    while(T--) {
        scanf("%d", &n);
        int tmp = 1;           // init.  
        for(int i = 1; i <=n; i++) {
            scanf("%d", &x);
            ans = tmp/gcd(tmp, x)*x;
            tmp = ans;
        }
        printf("%d\n", tmp);
    }
    return 0;
}

你可能感兴趣的:(HDU1019 Least Common Multiple)