zoukankan      html  css  js  c++  java
  • SRM遇到的一个数论技巧——最大公约数和最小公倍数的关系

    最大公约数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

    代码:

     1 #include <vector>
    2 #include <list>
    3 #include <map>
    4 #include <set>
    5 #include <queue>
    6 #include <deque>
    7 #include <stack>
    8 #include <bitset>
    9 #include <algorithm>
    10 #include <functional>
    11 #include <numeric>
    12 #include <utility>
    13 #include <sstream>
    14 #include <iostream>
    15 #include <iomanip>
    16 #include <cstdio>
    17 #include <cmath>
    18 #include <cstdlib>
    19 #include <ctime>
    20
    21 using namespace std;
    22
    23
    24 class FoxAndGCDLCM {
    25 public:
    26 long long gcd(long long a, long long b) {
    27 if(b == 0) return a;
    28 return gcd(b, a%b);
    29 }
    30
    31 long long get(long long G, long long L) {
    32
    33 if(L%G) return -1;
    34 long long i, x = L/G;
    35 long long ans = L;
    36
    37 for(i = 1; i*i <= x; ++i) {
    38 if(x%i) continue;
    39 if(gcd(i, x/i) == 1) {
    40 ans = min(ans, i + x/i);
    41 }
    42 }
    43 return ans*G;
    44 }
    45 };
    46
    47
    48
    49 //Powered by KawigiEdit 2.1.8 (beta) modified by pivanof!



  • 相关阅读:
    关于返回上一页功能
    Mybatis Update statement Date null
    SQLite reset password
    Bootstrap Validator使用特性,动态(Dynamic)添加的input的验证问题
    Eclipse使用Maven2的一次环境清理记录
    Server Tomcat v7.0 Server at localhost failed to start
    PowerShell一例
    Server Tomcat v7.0 Server at libra failed to start
    商标注册英语
    A glance for agile method
  • 原文地址:https://www.cnblogs.com/vongang/p/2418823.html
Copyright © 2011-2022 走看看