C++ 中数组乘积的约数计数
给定一个数组,比如 arr[],它包含任意大小的整型元素,任务是计算由数组所有元素相乘得到的数字的因数个数。
数组是一种数据结构,可以存储固定大小的相同类型元素的顺序集合。数组用于存储数据集合,但通常将数组视为相同类型变量的集合更有用。
例如
Input − int arr[] = {2, 3} Output − count is 4
解释 - 数组的乘积是 2 * 3 等于 6,6 的因数是 1、2、3、6。所以 6 总共有 4 个因数。
Input − int arr[] = {2, 3, 5} Output − count is 8
解释 - 数组的乘积是 2 * 3 * 5 等于 30,30 的因数是 1、2、3、5、6、10、15、30。所以 30 总共有 8 个因数。
下面程序中使用的方案如下
创建一个数组,比如 arr[]
使用 length() 函数计算数组的长度,该函数将根据数组中的元素返回一个整数值。
声明一个临时变量,比如 temp,将其设置为 1
开始循环,从 i 等于 0 开始,到 i 小于数组大小结束
将 temp 设置为 temp *= arr[i]
调用另一个函数,该函数将返回一个计数。
取一个临时变量来存储元素的计数。
开始循环,从 i 等于 1 开始,到 i 小于等于 mul 结束。
在循环内部,检查如果 temp % i == 0,则将 count 的值加 1。
返回 count
打印结果。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
#include <iostream> using namespace std; // Function to count number of factors int divisors(int N){ // Initialize result with 0 int result = 0; // Increment result for every factor // of the given number N. for (int i = 1; i <= N; ++i){ if (N % i == 0){ result++; } } return result; } int countmultiples(int arr_1[], int size){ // To multiply all elements of // the given array. int temp = 1; for (int i = 0; i < size; ++i){ temp *= arr_1[i]; } return divisors(temp); } // main function int main(){ int arr_1[] = { 5, 10, 15 }; int size = sizeof(arr_1) / sizeof(arr_1[0]); cout <<"count is "<<countmultiples(arr_1, size); return 0; }
输出
如果运行以上代码,将得到以下输出:
count is 16
广告