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
列印結果。
示例
#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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP