C++中統計至少能被另一個數組中的一個元素整除的元素個數


我們有兩個陣列,假設為arr_1[]和arr_2[],兩者都包含整數值,任務是計算至少能被另一個數組中的一個元素整除的元素個數。這意味著我們需要統計在第二個陣列arr_2中至少有一個因子的元素。

陣列是一種資料結構,可以儲存相同型別元素的固定大小的順序集合。陣列用於儲存資料集合,但通常將陣列視為相同型別變數的集合更有用。

例如

Input − int arr_1[] = {1, 2, 3, 4, 5}
      arr_2[] = {2, 6, 12, 15}
Output − count is 2

說明 − arr_1[]中有5個元素,arr_2[]中有4個元素。arr_1[]中的所有元素都能被arr_2[]中的元素整除。所以計數是5。

Input − int arr_1[] = {1, 2, 3, 4, 5}
      arr_2[] = {13, 11}
Output − count is 0

說明 − arr_1[]中有5個元素,arr_2[]中有2個元素。arr_1[]中的任何元素都不能被arr_2[]中的元素整除。所以計數是0。

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

  • 建立兩個陣列,例如arr_1[]和arr_2[]

  • 使用length()函式計算兩個陣列的長度,該函式將根據陣列中的元素返回整數值。

  • 取一個臨時變數來儲存元素的計數。

  • 建立一個無序集合變數,例如us

  • 開始迴圈,i從0開始,i小於第二個陣列的大小。

  • 在迴圈內,將arr_2[i]插入到us中。

  • 開始另一個迴圈,i從0開始,i小於第一個陣列的大小。

  • 在迴圈內,開始另一個迴圈,j從1開始,j*j <= arr_1[i]

  • 在此處檢查,如果arr_1[i]%j == 0,則檢查us.find(j)!=us.end() 或 us.find(arr_1[i]/j) != us.end(),如果是,則將計數加1

  • 否則,中斷迴圈

  • 返回計數

  • 列印結果。

示例

 線上演示

#include <iostream>
#include <unordered_set>
using namespace std;
// Function to count the number of elements
// in first array whose atleast one factor is
// present in the second array
int totalelements(int arr_1[], int size1, int arr_2[], int size2){
   // variable 'result' to count the number of elements
   int result = 0;
   // Hash of second array elements
   unordered_set<int> h;
   for (int i = 0; i < size2; i++){
      h.insert(arr_2[i]);
   }
   // traverse through array elements
   // and find its factors
   for (int i = 0; i < size1; i++){
      for (int j = 1; j * j <= arr_1[i]; j++){
         if (arr_1[i] % j == 0){
            // check if the factor is present in
            // second array using the h
            if ((h.find(j) != h.end()) || (h.find(arr_1[i] / j)!= h.end())){
               result++;
               break;
            }
         }
      }
   }
   return result;
}
// Main function
int main(){
   int arr_1[] = { 1, 2, 3, 4, 5 };
   int arr_2[] = { 2, 6, 12, 15 };
   int size1 = sizeof(arr_1) / sizeof(arr_1[0]);
   int size2 = sizeof(arr_2) / sizeof(arr_2[0]);
   cout <<"count is "<<totalelements(arr_1, size1, arr_2, size2);
   return 0;
}

輸出

如果我們執行上面的程式碼,我們將得到以下輸出:

count is 2

更新於:2020年5月15日

321 次瀏覽

開始您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.