您的位置:首页 > 其它

SRM遇到的一个数论技巧——最大公约数和最小公倍数的关系

2012-03-26 23:51 316 查看
最大公约数L和最小公倍数G的关系:

1、L%G == 0;

2、设A, B的最大公约数为G, 最小公倍数为L,则:

L/G = (A/G)*(B/G)

3、gcd(A/G, B/G) = 1;

题目:给出一对数A, B 的最大公约数G, 最小公倍数L。这里A, B有多种组合。,求A,B的一种组合使得A + B最小。如果没有则输出-1(SRM535 div2 500pt)

(G <= 10^12, L<=10^12)

猛的一看数据很大。不过用上前边的定理就可以解决了。

领X = L/G;

枚举A/G的值(不超过sqrt(X)),得到B/G的值。判断是否满足定理3。在所有满足的情况中找最小的ans = min(ans, (A/G + B/G))。最后结果为ans*G

代码:

#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>

using namespace std;

class FoxAndGCDLCM {
public:
long long gcd(long long a, long long b) {
if(b == 0)    return a;
return gcd(b, a%b);
}

long long get(long long G, long long L) {

if(L%G)    return -1;
long long i, x = L/G;
long long ans = L;

for(i = 1; i*i <= x; ++i) {
if(x%i)    continue;
if(gcd(i, x/i) == 1) {
ans = min(ans, i + x/i);
}
}
return ans*G;
}
};

//Powered by KawigiEdit 2.1.8 (beta) modified by pivanof!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: