Find prime factors of Array elements whose sum of exponents is divisible by K

Given an array arr[] of N positive integers and an integer K., The task is to create a set of prime numbers such that the sum of all the powers of prime numbers in the prime factorization of all the array elements is divisible by K.
Examples:

Input: arr[] = {1, 2, 3}, K = 1 
Output: {2, 3} 
Explanation: 
2 = 21 
3 = 31 
The power of 2 is 1 which is divisible by K(=1). 
The power of 2 is 1 which is divisible by K(=1).
Input: arr[] = {2, 2, 4, 8}, K = 10 
Output: {} 
Explanation: 
2 = 21 
2 = 21 
4 = 22 
8 = 23 
The power of 2 is (1 + 1 + 2 + 3) = 7 which is not divisible by K(=10). 
Thus, the output empty set.

Naive approach: The idea is to find all prime numbers less than or equal to the maximum element of the array arr[]. For each prime number count number of times, it divides the array element. If the value of count is divisible by K, then insert the prime number into the resultant set. At the end print elements of the set. 
Time Complexity: O(N*log(N)) 
Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach the idea is to precompute the count of all the prime factors of all the numbers. Below are the steps:

  1. Create the smallest prime factorization array spf[] up to the maximum number in the array. This step is used to precalculate the prime factors of a number.
  2. Traverse the given array arr[] and for each element find the sum of all the count of factors stored in spf[] array.
  3. For each sum of the power of a prime number in the above steps stored it frequency in a Map.
  4. Traverse the map if, for any number, frequency is divisible by K then store that number.
  5. Finally, print all the numbers stored in the above step.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach 
#include <iostream> 
#include <unordered_map> 
#include <vector> 
using namespace std; 
  
// To store the smallest prime 
// factor till 10^5 
int spf[10001]; 
  
// Function to compute smallest 
// prime factor array 
void spf_array(int spf[]) 
    // Initialize the spf array 
    // first element 
    spf[1] = 1; 
  
    for (int i = 2; i < 1000; i++) 
  
        // Marking smallest prime 
        // factor for every number 
        // to be itself 
        spf[i] = i; 
  
    // Separately marking smallest 
    // prime factor for every even 
    // number as 2 
    for (int i = 4; i < 1000; i += 2) 
        spf[i] = 2; 
  
    for (int i = 3; i * i < 1000; i++) { 
  
        // Checking if i is prime 
        if (spf[i] == i) { 
  
            // Marking SPF for all 
            // numbers divisible by i 
            for (int j = i * i; 
                j < 1000; j += i) 
  
                // Marking spf[j] if it is 
                // not previously marked 
                if (spf[j] == j) 
                    spf[j] = i; 
        
    
  
// Function that finds minimum operation 
void frequent_prime(int arr[], int N, 
                    int K) 
  
    // Create a spf[] array 
    spf_array(spf); 
  
    // Map created to store the 
    // unique prime numbers 
    unordered_map<int, int> Hmap; 
  
    // To store the result 
    vector<int> result; 
    int i = 0; 
  
    // To store minimum opeartions 
    int c = 0; 
  
    // To store every unique 
    // prime number 
    for (i = 0; i < N; i++) { 
  
        int x = arr[i]; 
        while (x != 1) { 
  
            Hmap[spf[x]] 
                = Hmap[spf[x]] + 1; 
            x = x / spf[x]; 
        
    
  
    // Erase 1 as a key because 
    // it is not a prime number 
    Hmap.erase(1); 
  
    for (auto x : Hmap) { 
  
        // First Prime Number 
        int primeNum = x.first; 
        int frequency = x.second; 
  
        // Frequency is divisible 
        // by K then insert primeNum 
        // in the result[] 
        if (frequency % K == 0) { 
            result.push_back(primeNum); 
        
    
  
    // Print the elements 
    // if it exists 
    if (result.size() > 0) { 
  
        for (auto& it : result) { 
            cout << it << ' '
        
    
    else
        cout << "{}"
    
  
// Driver Code 
int main() 
    // Given array arr[] 
    int arr[] = { 1, 4, 6 }; 
  
    // Given K 
    int K = 1; 
  
    int N = sizeof(arr) / sizeof(arr[0]); 
  
    // Function Call 
    frequent_prime(arr, N, K); 

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach 
import java.util.*;
  
class GFG{
      
// To store the smallest prime
// factor till 10^5
static int[] spf = new int[10001];
  
// Function to compute smallest
// prime factor array
static void spf_array(int spf[])
{
      
    // Initialize the spf array
    // first element
    spf[1] = 1;
  
    for(int i = 2; i < 1000; i++)
  
        // Marking smallest prime
        // factor for every number
        // to be itself
        spf[i] = i;
  
    // Separately marking smallest
    // prime factor for every even
    // number as 2
    for(int i = 4; i < 1000; i += 2)
        spf[i] = 2;
  
    for(int i = 3; i * i < 1000; i++)
    {
          
        // Checking if i is prime
        if (spf[i] == i) 
        {
              
            // Marking SPF for all
            // numbers divisible by i
            for(int j = i * i;
                    j < 1000; j += i)
  
                // Marking spf[j] if it is
                // not previously marked
                if (spf[j] == j)
                    spf[j] = i;
        }
    }
}
  
// Function that finds minimum operation
static void frequent_prime(int arr[], int N,
                                      int K)
{
      
    // Create a spf[] array
    spf_array(spf);
  
    // Map created to store the
    // unique prime numbers
    Map<Integer, Integer> Hmap = new TreeMap<>();
  
    // To store the result
    ArrayList<Integer> result = new ArrayList<>();
    int i = 0;
  
    // To store minimum opeartions
    int c = 0;
  
    // To store every unique
    // prime number
    for(i = 0; i < N; i++) 
    {
        int x = arr[i];
        while (x != 1
        {
            Hmap.put(spf[x],
                     Hmap.getOrDefault(spf[x], 0) + 1);
            x = x / spf[x];
        }
    }
  
    // Erase 1 as a key because
    // it is not a prime number
    Hmap.remove(1);
  
    for(Map.Entry<Integer,
                  Integer> x : Hmap.entrySet()) 
    {
          
        // First prime number
        int primeNum = x.getKey();
        int frequency = x.getValue();
  
        // Frequency is divisible
        // by K then insert primeNum
        // in the result[]
        if (frequency % K == 0)
        {
            result.add(primeNum);
        }
    }
  
    // Print the elements
    // if it exists
    if (result.size() > 0
    {
        for(Integer it : result)
        {
            System.out.print(it + " ");
        }
    }
    else
    {
        System.out.print("{}");
    }
}
  
// Driver code
public static void main (String[] args)
{
      
    // Given array arr[]
    int arr[] = { 1, 4, 6 };
      
    // Given K
    int K = 1;
      
    int N = arr.length;
      
    // Function call
    frequent_prime(arr, N, K);
}
}
  
// This code is contributed by offbeat

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
  
  // To store the smallest prime
  // factor till 10^5
  static int[] spf = new int[10001];
  
  // Function to compute smallest
  // prime factor array
  static void spf_array(int[] spf)
  {
  
    // Initialize the spf array
    // first element
    spf[1] = 1;
  
    for (int i = 2; i < 1000; i++)
  
      // Marking smallest prime
      // factor for every number
      // to be itself
      spf[i] = i;
  
    // Separately marking smallest
    // prime factor for every even
    // number as 2
    for (int i = 4; i < 1000; i += 2)
      spf[i] = 2;
  
    for (int i = 3; i * i < 1000; i++) 
    {
  
      // Checking if i is prime
      if (spf[i] == i) 
      {
  
        // Marking SPF for all
        // numbers divisible by i
        for (int j = i * i; j < 1000; j += i)
  
          // Marking spf[j] if it is
          // not previously marked
          if (spf[j] == j)
            spf[j] = i;
      }
    }
  }
  
  // Function that finds minimum operation
  static void frequent_prime(int[] arr, int N, int K)
  {
  
    // Create a spf[] array
    spf_array(spf);
  
    // Map created to store the
    // unique prime numbers
    SortedDictionary<int,
                     int> Hmap = new SortedDictionary<int
                                                      int>();
  
    // To store the result
    List<int> result = new List<int>();
    int i = 0;   
  
    // To store every unique
    // prime number
    for (i = 0; i < N; i++) 
    {
      int x = arr[i];
      while (x != 1) 
      {
        if (Hmap.ContainsKey(spf[x]))
          Hmap[spf[x]] = spf[x] + 1;
        else
          Hmap.Add(spf[x], 1);
        x = x / spf[x];
      }
    }
  
    // Erase 1 as a key because
    // it is not a prime number
    Hmap.Remove(1);
  
    foreach(KeyValuePair<int, int> x in Hmap)
    {
  
      // First prime number
      int primeNum = x.Key;
      int frequency = x.Value;
  
      // Frequency is divisible
      // by K then insert primeNum
      // in the result[]
      if (frequency % K == 0) 
      {
        result.Add(primeNum);
      }
    }
  
    // Print the elements
    // if it exists
    if (result.Count > 0) 
    {
      foreach(int it in result)
      {
        Console.Write(it + " ");
      }
    }
    else
    {
      Console.Write("{}");
    }
  }
  
  // Driver code
  public static void Main(String[] args)
  {
  
    // Given array []arr
    int[] arr = {1, 4, 6};
  
    // Given K
    int K = 1;
  
    int N = arr.Length;
  
    // Function call
    frequent_prime(arr, N, K);
  }
}
  
// This code is contributed by Rajput-Ji

chevron_right


Output: 
 



3 2


 

Time Complexity: O(M*log(M)), where M is the maximum element of the array. 
Auxiliary Space: O(M) 

competitive-programming-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : offbeat, Rajput-Ji