HDU-2028

Lowest Common Multiple Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 68649 Accepted Submission(s): 28449

Problem Description
求n个数的最小公倍数。

Input
输入包含多个测试实例,每个测试实例的开始是一个正整数n,然后是n个正整数。

Output
为每组测试数据输出它们的最小公倍数,每个测试实例的输出占一行。你可以假设最后的输出是一个32位的整数。

Sample Input
2 4 6
3 2 5 7

Sample Output
12
70

Author
lcy

Source
C语言程序设计练习(五)

心得体会:

刚做出来的时候AC了3次,找不到错误,最后仔细阅读代码发现ans = ans*m/temp; 这块ans*m若两个32位相乘时有可能爆int,所以在改为ans = ans/temp*m;就AC了

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

//求最大公约数的函数:
int gcd(int a,int b)
{
    if(b == 0)
        return a;
    return gcd(b,a%b);
} 
int main()
{
    int n;
    while(cin>>n)
    {
        int m,temp,ans = 1;
        for(int i = 0;i < n;i++)
        {
            cin>>m;
            temp = gcd(ans,m);
            ans = ans/temp*m;
        }
        cout<<ans<<endl;
    }
    return 0;
}
posted @ 2018-01-29 18:27  Western_Trail  阅读(166)  评论(0编辑  收藏  举报