Description
Write a program which computes the greatest common divisor (GCD) and the least common multiple (LCM) of given a and b (0 < a, b ≤ 2,000,000,000). You can supporse that LCM(a, b) ≤ 2,000,000,000.
Input
Input consists of several data sets. Each data set contains a and b separated by a single space in a line. The input terminates with EOF.
Output
For each data set, print GCD and LCM separated by a single space in a line.
Sample Input
8 6 50000000 30000000
Output for the Sample Input
2 24 10000000 150000000
题意:
给出 a 和 b(0 <= a,b <= 2000000000),算出 a 和 b 的最大公约数(GCD)和最小公倍数(LCM)。
思路:
GCD。LCM = (A * B)/ GCD。注意写法:
1.2 * 10 ^ 9 不会超int,故可以用 int 型,故 gcd 返回的值可以是 int;
2.LCM 的 A * B 的时候有可能会爆 int 故相除后乘,写成 A / GCD (A,B) * B,有可能最后相乘的时候也会爆 int ,所以最好将其一转化为long long;
3.不需要将 A 和 B 比较大小再GCD,因为当 A < B,第一次递归的时候 GCD(B,A % B)会等于 GCD(A,B)(因为 A % B == B)。
AC:
#include <stdio.h>
int gcd(int a,int b) {
return (b ? gcd(b,a % b): a);
}
int main() {
int a,b;
while(~scanf("%d%d",&a,&b)) {
printf("%d %lld\n",gcd(a,b),a / gcd(a,b) * (long long)b);
}
return 0;
}