HDU 1019 Least Common Multiple(三個注意的點)

1.優美的最大公約數的算法

int gcd(int a, int b) {
    return b?gcd(b, a%b):a;
}


2.溢出問題

兩個數是a,b最大公約數是p,最小公倍數是q
那麼有這樣的關係:ab=pq
所以q=ab/p,於是很多同學 a * b / p,這裏a * b可能會溢出。只要改一下運算順序就對了, a / p * b;


3.依次處理類的問題沒必要開數組,第一次多讀取一個值,然後依次往後處理即可

scanf("%d %d", &n, &temp);
        for (int i = 1; i < n; ++i) {
            scanf("%d", &x);
      temp = temp / gcd(temp, x) * x;
        }



代碼如下

#include<stdio.h>

int gcd(int a, int b) {
    return b?gcd(b, a%b):a;
}

int main(void)
{
    int T, n, x, temp;
    scanf("%d", &T);

    while (T--) {
    scanf("%d %d", &n, &temp);
        for (int i = 1; i < n; ++i) {
            scanf("%d", &x);
      temp = temp / gcd(temp, x) * x;
        }
        printf("%d\n", temp);
    }

    return 0;
}


發佈了81 篇原創文章 · 獲贊 39 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章