您好,欢迎访问一九零五行业门户网

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

suppose we have one array. we have to count how many of the elements present in the array prime number of times. so if the array is {1, 2, 2, 0, 1, 5, 2, 5, 0, 0, 1, 1}, then 1 is present 4 times, 2 is present 3 times, 0 is present 3 times, and 5 is present 2 times. so there are three elements {2, 0, 5} that have occurred prime number of times. so the count will be 3.
algorithmcountprimeoccurrence(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 countend
example#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
以上就是数组元素的频率是否为质数?的详细内容。
其它类似信息

推荐信息