HDOJ 2028 求多个数的最小公倍数

这是我的第一篇。。所以写一个近来AC出来最快的题。 见笑。

/**/
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <stack>
#include <queue>

typedef long long LL;
typedef unsigned long long ULL;
using namespace std;

inline int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b);}
int LCM(int a, int b) { return a / gcd(a,b) * b;}

int a[105];

int main()
{
	//freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
	int n, i;
	while(cin >> n) {
		for(i = 0; i < n; i++) {
			cin >> a[i];
		}
		int x = a[0];
		for(i = 1; i < n; i++) {
			x = LCM(x,a[i]);
			if(i == n-1)
				cout << x << endl;
		}
	}
	return 0;
}
/**/

inline内联函数,节省时间。

求gcd,LCM都是数论的基础知识,紫书上讲得超级清楚。要注意的是 a * b = gcd(a,b) * LCM(a,b);求LCM时,先做除法再做乘法,防止溢出。求所有数的lcm,如上。

猜你喜欢

转载自blog.csdn.net/wen__han/article/details/82227887