给定两个整数,任务是找到给定数字的所有公因数的计数。
Input : a = 12, b = 24
Output: 6
// all common divisors are 1, 2, 3,
// 4, 6 and 12
Input : a = 3, b = 17
Output: 1
// all common divisors are 1
Input : a = 20, b = 36
Output: 3
// all common divisors are 1, 2, 4
// C++ implementation of program
#include
using namespace std;
// Function to calculate gcd of two numbers
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// Function to calculate all common divisors
// of two given numbers
// a, b --> input integer numbers
int commDiv(int a, int b)
{
// find gcd of a, b
int n = gcd(a, b);
// Count divisors of n.
int result = 0;
for (int i = 1; i <= sqrt(n); i++) {
// if 'i' is factor of n
if (n % i == 0) {
// check if divisors are equal
if (n / i == i)
result += 1;
else
result += 2;
}
}
return result;
}
// Driver program to run the case
int main()
{
int a = 12, b = 24;
cout << commDiv(a, b);
return 0;
}
输出:
6
有关更多详细信息,请参阅关于两个数的公共除数的完整文章!
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。