Product of elements in an array having prime frequency
Last Updated :
19 Dec, 2022
Given an array arr[] of N elements, the task is to find the product of the elements which have prime frequencies in the array. Since, the product can be large so print the product modulo 109 + 7. Note that 1 is neither prime nor composite.
Examples:
Input: arr[] = {5, 4, 6, 5, 4, 6}
Output: 120
All the elements appear 2 times which is a prime
So, 5 * 4 * 6 = 120
Input: arr[] = {1, 2, 3, 3, 2, 3, 2, 3, 3}
Output: 6
Only 2 and 3 appears prime number of times i.e. 3 and 5 respectively.
So, 2 * 3 = 6
Approach:
- Traverse the array and store the frequencies of all the elements in a map.
- Build Sieve of Eratosthenes which will be used to test the primality of a number in O(1) time.
- Calculate the product of elements having prime frequency using the Sieve array calculated in the previous step.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
// Function to create Sieve to check primes
void SieveOfEratosthenes(bool prime[], int p_size)
{
// False here indicates
// that it is not prime
prime[0] = false;
prime[1] = false;
for (int p = 2; p * p <= p_size; p++) {
// If prime[p] is not changed,
// then it is a prime
if (prime[p]) {
// Update all multiples of p,
// set them to non-prime
for (int i = p * 2; i <= p_size; i += p)
prime[i] = false;
}
}
}
// Function to return the product of elements
// in an array having prime frequency
int productPrimeFreq(int arr[], int n)
{
bool prime[n + 1];
memset(prime, true, sizeof(prime));
SieveOfEratosthenes(prime, n + 1);
int i, j;
// Map is used to store
// element frequencies
unordered_map<int, int> m;
for (i = 0; i < n; i++)
m[arr[i]]++;
long product = 1;
// Traverse the map using iterators
for (auto it = m.begin(); it != m.end(); it++) {
// Count the number of elements
// having prime frequencies
if (prime[it->second]) {
product *= (it->first % MOD);
product %= MOD;
}
}
return (int)(product);
}
// Driver code
int main()
{
int arr[] = { 5, 4, 6, 5, 4, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << productPrimeFreq(arr, n);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
static int MOD = 1000000007;
// Function to create Sieve to check primes
static void SieveOfEratosthenes(boolean prime[],
int p_size)
{
// False here indicates
// that it is not prime
prime[0] = false;
prime[1] = false;
for (int p = 2; p * p <= p_size; p++)
{
// If prime[p] is not changed,
// then it is a prime
if (prime[p])
{
// Update all multiples of p,
// set them to non-prime
for (int i = p * 2;
i <= p_size; i += p)
prime[i] = false;
}
}
}
// Function to return the product of elements
// in an array having prime frequency
static int productPrimeFreq(int arr[], int n)
{
boolean []prime = new boolean[n + 1];
for (int i = 0; i < n; i++)
prime[i] = true;
SieveOfEratosthenes(prime, n + 1);
int i, j;
// Map is used to store
// element frequencies
HashMap<Integer,
Integer> mp = new HashMap<Integer,
Integer>();
for (i = 0 ; i < n; i++)
{
if(mp.containsKey(arr[i]))
{
mp.put(arr[i], mp.get(arr[i]) + 1);
}
else
{
mp.put(arr[i], 1);
}
}
long product = 1;
// Traverse the map using iterators
for (Map.Entry<Integer,
Integer> it : mp.entrySet())
{
// Count the number of elements
// having prime frequencies
if (prime[it.getValue()])
{
product *= (it.getKey() % MOD);
product %= MOD;
}
}
return (int)(product);
}
// Driver code
static public void main (String []arg)
{
int arr[] = { 5, 4, 6, 5, 4, 6 };
int n = arr.length;
System.out.println(productPrimeFreq(arr, n));
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 implementation of the approach
MOD = 1000000007
# Function to create Sieve to check primes
def SieveOfEratosthenes(prime, p_size):
# False here indicates
# that it is not prime
prime[0] = False
prime[1] = False
for p in range(2, p_size):
# If prime[p] is not changed,
# then it is a prime
if (prime[p]):
# Update all multiples of p,
# set them to non-prime
for i in range(2 * p, p_size, p):
prime[i] = False
# Function to return the product of elements
# in an array having prime frequency
def productPrimeFreq(arr, n):
prime = [True for i in range(n + 1)]
SieveOfEratosthenes(prime, n + 1)
i, j = 0, 0
# Map is used to store
# element frequencies
m = dict()
for i in range(n):
m[arr[i]] = m.get(arr[i], 0) + 1
product = 1
# Traverse the map using iterators
for it in m:
# Count the number of elements
# having prime frequencies
if (prime[m[it]]):
product *= it % MOD
product %= MOD
return product
# Driver code
arr = [5, 4, 6, 5, 4, 6]
n = len(arr)
print(productPrimeFreq(arr, n))
# This code is contributed by Mohit Kumar
C#
// C# implementation for above approach
using System;
using System.Collections.Generic;
class GFG
{
static int MOD = 1000000007;
// Function to create Sieve to check primes
static void SieveOfEratosthenes(bool []prime,
int p_size)
{
// False here indicates
// that it is not prime
prime[0] = false;
prime[1] = false;
for (int p = 2; p * p <= p_size; p++)
{
// If prime[p] is not changed,
// then it is a prime
if (prime[p])
{
// Update all multiples of p,
// set them to non-prime
for (int i = p * 2;
i <= p_size; i += p)
prime[i] = false;
}
}
}
// Function to return the product of elements
// in an array having prime frequency
static int productPrimeFreq(int []arr, int n)
{
bool []prime = new bool[n + 1];
int i;
for (i = 0; i < n; i++)
prime[i] = true;
SieveOfEratosthenes(prime, n + 1);
// Map is used to store
// element frequencies
Dictionary<int,
int> mp = new Dictionary<int,
int>();
for (i = 0 ; i < n; i++)
{
if(mp.ContainsKey(arr[i]))
{
var val = mp[arr[i]];
mp.Remove(arr[i]);
mp.Add(arr[i], val + 1);
}
else
{
mp.Add(arr[i], 1);
}
}
long product = 1;
// Traverse the map using iterators
foreach(KeyValuePair<int, int> it in mp)
{
// Count the number of elements
// having prime frequencies
if (prime[it.Value])
{
product *= (it.Key % MOD);
product %= MOD;
}
}
return (int)(product);
}
// Driver code
static public void Main (String []arg)
{
int []arr = { 5, 4, 6, 5, 4, 6 };
int n = arr.Length;
Console.WriteLine(productPrimeFreq(arr, n));
}
}
// This code is contributed by Princi Singh
JavaScript
<script>
// JavaScript implementation of the approach
let MOD = 1000000007;
// Function to create Sieve to check primes
function SieveOfEratosthenes(prime, p_size){
// False here indicates
// that it is not prime
prime[0] = false;
prime[1] = false;
for (let p = 2; p * p <= p_size; p++) {
// If prime[p] is not changed,
// then it is a prime
if (prime[p]) {
// Update all multiples of p,
// set them to non-prime
for (let i = p * 2; i <= p_size; i += p)
prime[i] = false;
}
}
return prime;
}
// Function to return the product of elements
// in an array having prime frequency
function productPrimeFreq(arr, n){
let prime = [];
for(let i = 0;i<n+1;i++){
prime.push(true);
}
prime = SieveOfEratosthenes(prime, n + 1);
let i, j;
// Map is used to store
// element frequencies
let m = new Map();
for (i = 0; i < n; i++){
if(m[arr[i]])
m[arr[i]]++;
else
m[arr[i]] = 1;
}
let product = 1;
// Traverse the map using iterators
for (var it in m) {
// Count the number of elements
// having prime frequencies
if (prime[m[it]]) {
product *= (it % MOD);
product %= MOD;
}
}
return (product);
}
// Driver code
let a = [ 5, 4, 6, 5, 4, 6 ];
let len = a.length;
document.write(productPrimeFreq(a, len));
</script>
Time Complexity: O(n * log(log(n))
Auxiliary Space: O(n), where n is the size of the given array.
Similar Reads
XOR of elements in an array having prime frequency Given an array arr[] of N elements, the task is to find the xor of the elements which have prime frequencies in the array. Note that 1 is neither prime nor composite. Examples: Input: arr[] = {5, 4, 6, 5, 4, 6} Output: 7 Explanation: All the elements appear 2 times which is a prime So, 5 ^ 4 ^ 6 = 7
7 min read
Sum of elements in an array having prime frequency Given an array arr, the task is to find the sum of the elements which have prime frequencies in the array. Note: 1 is neither prime nor composite.Examples: Input: arr[] = {5, 4, 6, 5, 4, 6} Output: 15 All the elements appear 2 times which is a prime So, 5 + 4 + 6 = 15Input: arr[] = {1, 2, 3, 3, 2, 3
7 min read
Sum of elements in an array having composite frequency Given an array of integers arr of size N, the task is to find the sum of the elements which have composite frequencies in the array.Examples: Input: arr[] = {1, 2, 1, 1, 1, 3, 3, 2} Output: 1 1 appears 4 times which is a composite. All other elements 2 and 3 appears 2 times which is prime. So, the a
11 min read
Product of every Kâth prime number in an array Given an integer 'k' and an array of integers 'arr' (less than 10^6), the task is to find the product of every K'th prime number in the array. Examples: Input: arr = {2, 3, 5, 7, 11}, k = 2 Output: 21 All the elements of the array are prime. So, the prime numbers after every K (i.e. 2) interval are
12 min read
Array elements with prime frequencies Given a string. The task is to find the count of characters whose number of occurrences is prime. Examples: Input : str = "geeksforgeeks" Output : 3 Count of occurrences of characters are: g -> 2 e -> 4 k -> 2 s -> 2 f -> 1 o -> 1 r -> 1 So, g, k and s occurs prime number of tim
7 min read
Sum and Product of Prime Frequencies of Characters in a String Given a string str containing only lowercase English alphabets, the task is to find the sum and product of all the prime frequencies of the characters in str. Examples: Input: str = "geeksforgeeks" Output: 6, 8 Only characters 'g', 'k' and 's' have prime frequencies i.e. 2 + 2 + 2 = 6 and 2 * 2* 2 =
7 min read
Product of all prime numbers in an Array Given an array arr[] of N positive integers. The task is to write a program to find the product of all the prime numbers of the given array. Examples: Input: arr[] = {1, 3, 4, 5, 7} Output: 105 There are three primes, 3, 5 and 7 whose product = 105. Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 210 N
11 min read
POTD Solutions | 1 Novâ 23 | Frequencies of Limited Range Array Elements View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Frequency Counting algorithm but will also help you bui
7 min read
Find the array element having equal count of Prime Numbers on its left and right Given an array arr[] consisting of N positive integers, the task is to find an index from the array having count of prime numbers present on its left and right are equal. Examples: Input: arr[] = {2, 3, 4, 7, 5, 10, 1, 8}Output: 2Explanation: Consider the index 2, then the prime numbers to its left
13 min read
Print characters having prime frequencies in order of occurrence Given a string str containing only lowercase characters. The task is to print the characters having prime frequency in the order of their occurrence. Note that repeated elements with prime frequencies are printed as many times as they occur in order of their occurrence. Examples: Input: str = "geeks
11 min read