您的位置:首页 > 其它

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

2014-03-03 21:28 239 查看
题目描述:

给定两个正整数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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: