ACM_最小公倍数

Lowest Common Multiple Plus

Time Limit: 2000/1000ms (Java/Others)

Problem Description:

求n个数的最小公倍数。

Input:

输入包含多个测试实例,每个测试实例的开始是一个正整数n(2<=n<=100),然后是n个正整数(数字均大于0)。

Output:

为每组测试数据输出它们的最小公倍数,每个测试实例的输出占一行。你可以假设最后的输出是一个64位的整数。

Sample Input:

2 3 4 
3 23 45 2

Sample Output:

12
2070
解题思路:求n个数的最小公倍数,(其中n>=2),先求出这两个数的最大公约数,再利用这两个数的乘积等于这两个数的最小公倍数和最大公约数的乘积即可求出n个数的最小公倍数。
设两个数是a,b最大公约数是p,最小公倍数是q,则ab=pq,即q=ab/p(q=a/p*b或q=b/p*a)。本题就是根据这样的关系来求最小公倍数的。
AC代码:
 1 #include<iostream>
 2 using namespace std;
 3 typedef long long LL ;
 4 LL gcd(LL a,LL b) //求两个数的最大公约数
 5 {
 6     return b ? gcd(b,a%b):a;
 7 }
 8 LL lcm(LL m,LL g)  //求两个数的最小公倍数
 9 {
10     return m/gcd(m,g)*g;
11 }
12 int main()
13 {
14     int n;
15     LL lowest,q;
16     while(cin>>n){
17         cin>>q>>lowest;
18         lowest=lcm(q,lowest);
19         n-=2;
20         while(n--){
21             cin>>q;
22             lowest=lcm(q,lowest);
23         }
24         cout<<lowest<<endl;
25     }
26     return 0;
27 }
 
posted @ 2018-04-10 22:10  霜雪千年  阅读(1343)  评论(0编辑  收藏  举报