GCD & LCM Inverse
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 9922 | Accepted: 1841 |
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
/* 已知a,b的最大公约数GCD和最小公倍数LCM,如何求a,b?如有多组解,则输出a+b和为最小的那组解, GCD和LCM的最大可达到 2^63, 其基本方法是先将LCM/GCD,再把该值拿去分解成两数相乘,由于数值范围达到64位,~~~~ */ //经典算法(超时) #include<stdio.h> #include<math.h> int GCD(long long a,long long b)//求最大公约数的递归算法 { return b==0?a:GCD(b,a%b); } /*int GCD(long long a,long long b)//求最大公约数的循环算法 { long long r; while(b!=0) { r=a%b; a=b; b=r; } return a; }*/ int main() { long long a,b,c,i; while(scanf("%lld%lld",&a,&b)!=EOF) { c=b/a; for(i=sqrt(c+0.5);i>=1;i--) { if(c%i==0&&GCD(i,c/i)==1)//GCD(a,b)==1说明a,b互质 { printf("%lld %lld\n",a*i,c/i*a); break; } } } return 0; } /* 1, p,q为两个正整数, 2,GCD(p,q)=x, 3,LCM(p.q)=y; 求p,q. a*b=GCD*LCM =>(a/GCD)*(b/GCD)=LCM, 这样可将a,b(也就是题目中的p,q)的范围大大缩小, 并发现,a>GCD,b?LCM互质(互质是指n个数的最大公因数是1,n个数互质), 根据这条性质,可以排除更多种情况。 */