Loading

Least Common Multiple (最小公倍数,先除再乘)

 
思路: 求第一个和第二个元素的最小公倍数,然后拿求得的最小公倍数和第三个元素求最小公倍数,继续下去,直到没有元素
注意:通过最大公约数求最小公倍数的时候,先除再乘,避免溢出
 
 1 #include <iostream>
 2 #include <cmath>
 3 #include <cstdio>
 4 #include <vector>
 5 #include <string.h>
 6 #include <string>
 7 #include <algorithm>
 8 
 9 using namespace std;
10 
11 int gcd(int a, int b)
12 {
13     return b == 0 ? a : gcd(b, a%b); 
14 }
15 
16 int main() 
17 {
18     int n;
19     while(cin >> n)
20     {
21         while(n--)
22         {
23             int m, a, ans;
24             cin >> m;
25             cin >> a;
26             ans = a;    // 当前的最小公倍数
27             while(--m)
28             {
29                 cin >> a;
30                 ans = ans * (a / gcd(ans, a));  // 这里如果先乘后除的话,可能会出现超出int限制的数。导致提交后WA 
31             }
32             cout << ans << endl;
33         }
34     }
35     
36     return 0;
37 }

 

posted @ 2019-07-03 10:27  拾月凄辰  阅读(356)  评论(0编辑  收藏  举报