C++ 中給定元素個數的矩陣(不同階數)計數


給定元素的總數,任務是計算可以使用給定資料形成的不同階數矩陣的總數。矩陣的階數為 mxn,其中 m 為行數,n 為列數。

輸入 − int numbers = 6

輸出 −可以使用給定元素個數形成的不同階數矩陣的個數為:4

解釋 − 給定矩陣的任意階數可以包含的元素總數為 6。因此,包含 6 個元素的可能的矩陣階數為 (1, 6)、(2, 3)、(3, 2) 和 (6, 1),共有 4 個。

輸入 − int numbers = 40

輸出 −可以使用給定元素個數形成的不同階數矩陣的個數為:8

解釋 − 給定矩陣的任意階數可以包含的元素總數為 40。因此,包含 40 個元素的可能的矩陣階數為 (1, 40)、(2, 20)、(4, 10)、(5, 8)、(8, 5)、(10, 4)、(20, 2) 和 (40, 1),共有 8 個。

下面程式中使用的方案如下

  • 輸入可用於形成不同階數矩陣的元素總數。

  • 將資料傳遞給函式以進行進一步計算

  • 使用一個臨時變數 count 來儲存不同階數矩陣的計數

  • 從 i 到 1 開始迴圈到 number

  • 在迴圈內部,檢查 IF number % i = 0 則將 count 加 1

  • 返回 count

  • 列印結果

示例

 即時演示

#include <iostream>
using namespace std;
//function to count matrices (of different orders) with given number of elements
int total_matrices(int number){
   int count = 0;
   for (int i = 1; i <= number; i++){
      if (number % i == 0){
         count++;
      }
   }
   return count;
}
int main(){
   int number = 6;
   cout<<"Count of matrices of different orders that can be formed with the given number of elements are: "<<total_matrices(number);
   return 0;
}

輸出

如果執行以上程式碼,它將生成以下輸出:

Count of matrices of different orders that can be formed with the given number of elements are: 4

更新於: 2020年11月2日

199 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告