两个数的公共因子的 C++ 程序?
在这里,我们将了解如何获得两个数的公共因子的数量。我们不会找到所有公共因子,但是我们会计算一共有多少公共因子。如果两个数字类似于 12 和 24,那么公共因子就是 1、2、3、4、6、12。因此有 6 个公共因子,所以答案是 6。
算法
countCommonDivisor(a, b)
begin count := 0 gcd := gcd of a and b for i := 1 to square root of gcd, do if gcd is divisible by 0, then if gcd / i = i, then count := count + 1 else count := count + 2 enf if end if done return count end
示例
#include<iostream>
#include<cmath>
using namespace std;
int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b%a, a);
}
int countCommonDivisors(int a,int b) {
int gcd_val = gcd(a, b); //get gcd of a and b
int count = 0;
for (int i=1; i<=sqrt(gcd_val); i++) {
if (gcd_val%i==0) { // when'i' is factor of n
if (gcd_val/i == i) //if two numbers are same
count += 1;
else
count += 2;
}
}
return count;
}
main() {
int a = 12, b = 24;
cout << "Total common divisors: " << countCommonDivisors(a, b);
}输出
The differences array: 6 5 10 1
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP