2014年王道论坛研究生机试练习赛(二):题目1493:公约数

题目描述:

给定两个正整数a,b(1<=a,b<=100000000),计算他们公约数的个数。
如给定正整数8和16,他们的公约数有:1、2、4、8,所以输出为4。

输入:

输入包含多组测试数据,每组测试数据一行,包含两个整数a,b。

输出:

对于每组测试数据,输出为一个整数,表示a和b的公约数个数。

样例输入:
8 16
22 16
样例输出:
4
2
Hint:

本题要利用一个定理:公约数是最大公约数的约数。先求出两个数字的最大公约数,然后用开根号算法求出公约数的个数。

代码如下:

#include <iostream>
#include<vector>
#include<algorithm>
#include<functional>
#include<iterator>
#include<cstdio>
using namespace std;
int gcd(int a, int b);
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("D:\\in.txt", "r", stdin);
    freopen("D:\\out.txt","w",stdout);
#endif
    int a(0), b(0);
    int count(0), max(0), i(0);
    while (cin>>a>>b)
    {
        
        max = gcd(a,b);
        count = 0;
        for (i = 1; i*i < max; i++)
        {
            if (max%i == 0)
                count += 2;
        }
        if (i*i == max)
            count++;
        printf("%d\n", count);
    }
    return 0;
}
int gcd(int a, int b)
{
    while (b != 0)
    {
        int t = a%b;
        a = b;
        b = t;
    }
    return a;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值