首頁  >  文章  >  後端開發  >  數組元素的頻率是否為質數?

數組元素的頻率是否為質數?

WBOY
WBOY轉載
2023-08-27 23:37:061133瀏覽

數組元素的頻率是否為質數?

假設我們有一個陣列。我們必須計算數組中元素出現的質數次數。因此,如果數組為 {1, 2, 2, 0, 1, 5, 2, 5, 0, 0, 1, 1},則 1 出現 4 次,2 出現 3 次,0 出現 3 次, 5 出現了2 次。因此,存在出現了質數次的三個元素 {2, 0, 5}。所以計數將為 3。

##演算法

countPrimeOccurrence(arr, n)

Begin
   count := 0
   define map with int type key and int type value
   for each element e in arr, do
      increase map.key(arr).value
   done
   for each key check whether the value corresponding the value is prime or not, if prime, then increase count.
   return count
End

範例

#include <iostream>
#include <map>
using namespace std;
bool isPrime(int n){
   for(int i = 2; i<=n/2; i++){
      if(n % i == 0){
         return false;
      }
   }
   return true;
}
int countPrimeOcurrence(int arr[], int n){
   int count = 0;
   map<int, int> freq_map;
   for(int i = 0; i<n; i++){
      freq_map[arr[i]]++; //increase the frequency
   }
   for (auto it = freq_map.begin(); it != freq_map.end(); it++) {
      if (isPrime(it->second))
         count++;
   }
   return count;
}
int main() {
   int arr[] = {1, 2, 2, 0, 1, 5, 2, 5, 0, 0, 1, 1};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "Prime frequency count: " << countPrimeOcurrence(arr, n);
}

輸出

Prime frequency count: 3

以上是數組元素的頻率是否為質數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除