HDU 2028 Lowest Common Multiple Plus,求一串數字的最小公倍數

鹹魚的我,過會去抓白秋煉。

首先是參考大佬的AC代碼,加上自己的修改(輸入中含有0的處理)

#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
int GCD(int a,int b){
    return b==0?a:GCD(b,a%b);
}
int main(){
    int n;
    int max1,x,i;
    while(~scanf("%d",&n)){
        max1=1;
        for(i=0;i<n;i++){
            cin>>x;
            if(x==0){
                max1=0;
                while(i<n){
                    cin>>x;
                    i++;
                }
                break;
            }
            max1=x/GCD(x,max1)*max1;
        }
        cout<<max1<<endl;
    }
    return 0;
}

 

這是我的

下面是大佬的

#include <iostream>
using namespace std;
int GCD(int x,int y)
{
    return y==0?x:GCD(y,x%y);
}
int main()
{
    int n,x;
    while(cin>>n)
    {
        int ans=1;
        for(int i=0;i<n;i++)
        {
            cin>>x;
            ans=x/GCD(ans,x)*ans;
        }
         cout<<ans<<endl;

    }
    return 0;
}

 

方法:就是,迭代到頂層,大佬的寫法令人耳目一新。

思路:最小公倍數(X,Y) * 最大公約數(X,Y)=X*Y

先除後乘可以避免超界,或者用long int;

附帶一份錯誤代碼(無法解決 輸入數據 5 ,2 3 4 6 9)

正確答案 36  錯誤代碼的輸出是 1296(即36^2,即2*3*4*6*9),原因是沒有用乘積一邊乘一邊除以因數

#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
long int zd(int a,int b){
    int i=0;
    while(a%b!=0){
        i=a%b;
        a=b;
        b=i;
    }
    return b;
}

int main(){
    int n;
    int a,b;
    int c[100]={0};
    long long int max1;
    while(~scanf("%d",&n)){
        max1=1;
        for(int i=0;i<n;i++){
            cin>>c[i];
            if(c[i] == 0){
                max1=0;
                break;
            }
            max1*=c[i];
        }
        if(max1==0){
            cout<<0<<endl;
            break;
        }
        a=c[0];
        for(int i=1;i<n;i++){
            b=c[i];
            a=zd(a,b);
            max1/=a;
        }
        cout<<max1<<endl;

    }
    return 0;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章