Array elements with prime frequencies in C++?

C++Server Side ProgrammingProgramming

Array is a container of elements of same data type.

Prime Frequencies means that the number of occurrence of the element of the array is a prime number.

So, based on these definitions the problem to find array elements with prime frequencies. We are given a string of array. We have to find the frequency of characters and check if frequency is prime and then count elements that have prime frequencies.

Let’s take an example,

Input: str = “helloworld”
Output: 2

Explanation

Count of occurrences of characters are −

h -> 1
e -> 1
l -> 3
o -> 2
w-> 1
r -> 1
d -> 1

l occurs prime number of times i.e. 3 and o occurs prime number of times i.e. 2.

Start traversing the string and count the occurrences of each character using a map in C++ and check whether an occurrence is prime or not. If prime then increment the count otherwise not.

Algorithm

To check for prime frequency of elements we will check for the occurrence of elements of and check if the count is prime or not. For this we will take maps under consideration.

Example

 Live Demo

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int check_prime(int n) {
   if (n <= 1)
      return 0;
   if (n <= 3)
      return 1;
   if (n % 2 == 0 || n % 3 == 0)
      return 0;
   for (int i = 5; i * i <= n; i = i + 6)
      if (n % i == 0 || n % (i + 2) == 0)
         return 0;
      return 1;
}
int countPrimeFrequent(string s) {
   int count = 0;
   unordered_map<char, int> mp;
   for (int i = 0; i < s.length(); i++)
      mp[s[i]]++;
   for (auto it = mp.begin(); it != mp.end(); it++) {
      if (check_prime(it->second))
         count++;
   }
   return count;
}
int main() {
   string s = "helloworld";
   cout << countPrimeFrequent(s);
   return 0;
}

Output

The repeat elements of the array are : 2
raja
Updated on 04-Oct-2019 08:22:18

Advertisements