最小公倍数(HDU - 1019)[上] [LCMの単純な番号ユークリッド] [ユークリッド]
タグ:講義のトピックにストップを取得
タイトル説明
The least common multiple (LCM) of a set of positive integers is the smallest positive integer which is divisible by all the numbers in the set. For example, the LCM of 5, 7 and 15 is 105.
入力
入力は複数の問題がインスタンスで構成されます。入力の最初の行は、問題のインスタンスの数を示す単一の整数を含むであろう。各インスタンスは、Mは集合内の整数の数であり、N1 ... NMは整数でフォームM N1、N2、N3 ... nmでの単一の行からなります。すべての整数は正であり、32ビット整数の範囲内にあるであろう。
出力
各問題例えば、出力対応LCMを含む単一の行。すべての結果は、32ビット整数の範囲にあるであろう。
サンプル入力
2
3 5 7 15
6 4 10296 936 1287 792 1
サンプル出力
105
10296
問題の意味
いくつかの数字を考えると、これらの数値の最小公倍数を見つけます。
解決
これは、ユークリッドユークリッドタイトルの基盤です。あなたは常に最小公倍数を求めている平野GCDアルゴリズムを使用することができます。
コードで
/*
Problem
HDU - 1019
Status
Accepted
Memory
1372kB
Length
466
Lang
G++
Submitted
2019-11-25 22:13:37
Shared
RemoteRunId
31637683
*/
#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b)
{
return b? gcd(b, a % b): a;
}
int lcm(int a, int b)
{
return a / gcd(a, b) * b; //注意此处不是 a * b / gcd,这样容易爆int.
}
int main()
{
int times;
scanf("%d", ×);
while(times --){
int n;
int t1, t2;
scanf("%d%d", &n, &t1);
for(int i = 1; i < n; i ++){
scanf("%d", &t2);
t1 = lcm(t1, t2); //不断地将前面求得的最小公倍数当作a,新输入的数当作b,继续求最小公倍数.
}
printf("%d\n", t1);
}
return 0;
}