GCD and LCM(数学 + GCD)

 

GCD and LCM
Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%lld & %llu

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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值