1. 程式人生 > >數學演算法:求多個數的最小公倍數

數學演算法:求多個數的最小公倍數

解體心得:
1、一開始我的演算法是找出最大的那個數,再將那個數一倍一倍的相加,但是會超時,因為題目的限制是32bits。(過於天真)
2、運用小學奧數的演算法,多個數的最小公倍數,先將兩個數的最小公倍數求出,再與後面的數求最小公倍數。兩個數的最小公倍數,可以先將兩個數相乘再除兩個數的最小公因數。為了避免溢位,可以先相除再相乘。
3、有一個比較簡單的求最大公因數的庫函式呼叫(__gcd(int a,int b)),但不是標準庫,標頭檔案使用萬能標頭檔案。

題目:

Problem Description
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.



Input
Input will consist of multiple problem instances. The first line of the input will contain a single integer indicating the number of problem instances. Each instance will consist of a single line of the form m n1 n2 n3 ... nm where m is the number of integers in the set and n1 ... nm are the integers. All integers will be positive and lie within the range of a 32-bit integer.


Output
For each problem instance, output a single line containing the corresponding LCM. All results will lie in the range of a 32-bit integer.


Sample Input
2
3 5 7 15
6 4 10296 936 1287 792 1


Sample Output
105
10296


Source
East Central Northmerica 2003, Practice 
#include<bits/stdc++.h>
using namespace std;
//為了防止溢位全開long long,gcd函式是找出兩個數的最大公因數(輾轉相除法);
long long gcd(long long a,long long k)
{
    if(k == 0)
        return a;
    else
        return gcd(k,a%k);
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        long
long k,cnt,a; a = cnt = 1; while(n--) { cin>>k;//一邊輸入一邊計算,節省時間 cnt = a/gcd(a,k)*k;//先除後乘防止溢位; a = cnt; } cout<<cnt<<endl; } }

求最大公因數的庫函式使用:

#include<bits/stdc++.h>
//好像只能使用這個標頭檔案
using namespace std
; int main() { int a,b; while(scanf("%d%d",&a,&b)!=EOF) { printf("%d\n",__gcd(a,b)); //不是標準庫中的函式 } }