GCD & LCM Inverse(目前超时)

来源:互联网 发布:图片php 如何保存 编辑:程序博客网 时间:2024/06/05 11:34
GCD & LCM Inverse
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 13128 Accepted: 2424

Description

Given two positive integers a and b, we can easily calculate the greatest common divisor (GCD) and the least common multiple (LCM) of a and b. But what about the inverse? That is: given GCD and LCM, finding a and b.

Input

The input contains multiple test cases, each of which contains two positive integers, the GCD and the LCM. You can assume that these two numbers are both less than 2^63.

Output

For each test case, output a and b in ascending order. If there are multiple solutions, output the pair with smallest a + b.

Sample Input

3 60

Sample Output

12 15

Source


解题思路:

给你gcd(a,b)和lcm(a,b),让你找最小的a和b。
因为(a*b)/gcd=lcm.那么(a/gcd*b/gcd)*gcd=lcm因此(a/gcd*b/gcd)=lcm/gcd。题目即可转换为把lcm/gcd分解成两个互质的数使这两个数和最小,只需要将key=lcm/gcd整数分解,然后dfs一下即可得到结果。


代码:

#include<iostream>
#include<cmath>
using namespace std;
long long GCD(long long a,long long b)//求最大公约数的循环算法  

    long r; 
    while(b!=0) 
    { 
        r=a%b; 
        a=b; 
        b=r; 
    } 
    return a; 
}
int main()
{
long long c,a,b,i;
while(cin>>a>>b)
{
c=b/a;
for(i=(long long)sqrt(c+0.5);i>0;i--)
{
if(c%i==0&&GCD(i,c/i)==1)
{
cout<<a*i<<" "<<c/i*a<<endl;
break;
}
}
}
}

0 0