首页 > 后端开发 > C++ > 正文

数组元素的频率是否为质数?

WBOY
发布: 2023-08-27 23:37:06
转载
1155 人浏览过

数组元素的频率是否为质数?

假设我们有一个数组。我们必须计算数组中元素出现的素数次数。因此,如果数组为 {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
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!