HDU1019 Least Common Multiple

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1019

用辗转相除法求最小公倍数时要注意应该用a/y*b,若用a*b/y,则可能会数据溢出。

#include<iostream>
#include 
<vector>
using namespace std;

int LCM(long x,long y)
{
    
long temp; 
    
long a,b; 
    a
=x; 
    b
=y; 
    
while(x%y!=0
    

        temp
=x%y; 
        x
=y; 
        y
=temp; 
    }
 
    
return a/y*b; 
}

void doProcess(vector<long>& v)
{
    
if (v.size()==1)
    
{//只有一个数据
        cout<<v[0]<<endl;
        
return;
    }

    
int temp = LCM(v[0],v[1]);
    
for (int i=2;i<v.size();++i)
    
{
        temp 
= LCM(temp,v[i]);
    }

    cout
<<temp<<endl;
}

int main()
{
    
int caseNum,i,j,n,tmp;
    
while (cin>>caseNum)
    
{
        
for (i=0;i<caseNum;++i)
        
{
            cin
>>n;
            vector
<long> numVect;
            
for (j=1;j<=n;++j)
            
{
                cin
>>tmp;
                numVect.push_back(tmp);
            }

            doProcess(numVect);
        }

    }

    
return 0;
}

posted on 2008-01-04 21:02  Phinecos(洞庭散人)  阅读(845)  评论(1编辑  收藏  举报

导航