Least Common Multiple(HDU - 1019 )

版权声明:版权所有--转载的小伙伴请告知博主并注明来源哦~ https://blog.csdn.net/u011145745/article/details/81981803

Least Common Multiple

HDU - 1019 

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

Hint:求n个数的最小公因子

示例代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int a[10000000];
int main()
{
    int t, n, i, num, flag;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &n);
        num = 0;
        for(i = 0; i < n; i++)
        {
            scanf("%d", &a[i]);
            if(num < a[i]) num = a[i];
        }
        int x = num; // 把最大值存下来
        while(1)
        {
            flag = 1;
            for(i = n - 1; i >= 0; i--)
            {
                if(a[i] == 1) continue;
                if(num % a[i] != 0)
                {
                    flag = 0;
                    num += x;  // 直接最大值的整数倍变化,开始直接num++会超时
                    i = n;
                    break;
                }
            }
            if(flag) break;
        }
        printf("%d\n", num);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/u011145745/article/details/81981803