Count distinct prime factors for each element of an array

Given an array arr[] of size N, the task is to find the count of distinct prime factors of each element of the given array.
Examples:
Input: arr[] = {6, 9, 12}
Output: 2 1 2
Explanation:
- 6 = 2 × 3. Therefore, count = 2
- 9 = 3 × 3. Therefore, count = 1
- 12 = 2 × 2 × 3. Therefore, count = 2
The count of distinct prime factors of each array element are 2, 1, 2 respectively.
Input: arr[] = {4, 8, 10, 6}
Output: 1 1 2 2
Naive Approach: The simplest approach to solve the problem is to find the distinct prime factors of each array element. Then, print that count for each array element.Â
steps to implement-
- Run a loop over the given array to find the count of distinct prime factors of each element
- For finding the count of distinct prime factors of each element-
- Initialize a variable count with a value of 0
- First, check if the number can be divided by 2. If it can be then divide it by 2 till it can be divided and after that increment the count by 1.
- Then check for all odd numbers from 3 till its square root that it can divide the number or not
- If any odd number can divide then it should divide till it can and after that increment count by 1 for each odd number
- In last, if still we have number>2 then this number that is remaining is any prime number so increment count by 1
- In the last print/return the count
Code-
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// A function to provide count of//distinct prime factor of a given numberint primeFactors(int n){    //To store count of distinct prime factor of given number    int count=0;         //Boolean variable to check an element    //is included in its prime factor or not    bool val=false;         // Remove all 2s that can be prime factor of n    while (n % 2 == 0)    {          val=true;        n = n/2;    }         //If 2 is included    if(val==true){count++;}      // n must be odd at this point. So we can skip    // one element (Note i = i +2)    for (int i = 3; i <= sqrt(n); i = i + 2)    {        //To check whether i is included in prime factor        val=false;                 // While i divides n,divide n        while (n % i == 0)        {            val=true;            n = n/i;        }        //If i is included in prime factor        if(val==true){count++;}    }          // This condition is to handle the case when n    // is a prime number greater than 2    if (n > 2){       count++;     }      return count; }Â
// Function to get the distinct// factor count of arr[]void getFactorCount(int arr[],                    int N){    //Traverse every array element    for(int i=0;i<N;i++){        cout<<primeFactors(arr[i])<<" ";    }}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 6, 9, 12 };Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â Â Â Â getFactorCount(arr, N);Â Â Â Â return 0;} |
Java
import java.util.*;Â
public class Main {    // A function to provide count of    // distinct prime factors of a given number    static int primeFactors(int n) {        // To store the count of distinct prime factors of the given number        int count = 0;Â
        // Boolean variable to check if an element is included in its prime factor or not        boolean val = false;Â
        // Remove all 2s that can be prime factors of n        while (n % 2 == 0) {            val = true;            n = n / 2;        }Â
        // If 2 is included        if (val) {            count++;        }Â
        // n must be odd at this point. So we can skip one element (Note i = i + 2)        for (int i = 3; i <= Math.sqrt(n); i = i + 2) {            // To check whether i is included in prime factor            val = false;Â
            // While i divides n, divide n            while (n % i == 0) {                val = true;                n = n / i;            }Â
            // If i is included in the prime factor            if (val) {                count++;            }        }Â
        // This condition is to handle the case when n is a prime number greater than 2        if (n > 2) {            count++;        }Â
        return count;    }Â
    // Function to get the distinct factor count of arr[]    static void getFactorCount(int[] arr, int N) {        // Traverse every array element        for (int i = 0; i < N; i++) {            System.out.print(primeFactors(arr[i]) + " ");        }    }Â
    public static void main(String[] args) {        int[] arr = { 6, 9, 12 };        int N = arr.length;        getFactorCount(arr, N);    }} |
Python3
import mathÂ
# A function to provide count of distinct prime factor of a given numberdef prime_factors(n):    # To store count of distinct prime factors of the given number    count = 0         # Boolean variable to check if an element is included in its prime factors or not    val = False         # Remove all 2s that can be prime factors of n    while n % 2 == 0:        val = True        n = n // 2         # If 2 is included    if val == True:        count += 1Â
    # n must be odd at this point. So we can skip one element (Note i = i + 2)    for i in range(3, int(math.sqrt(n)) + 1, 2):        # To check whether i is included in prime factors        val = False                 # While i divides n, divide n        while n % i == 0:            val = True            n = n // i                 # If i is included in prime factors        if val == True:            count += 1         # This condition is to handle the case when n is a prime number greater than 2    if n > 2:        count += 1Â
    return countÂ
# Function to get the distinct factor count of arr[]def get_factor_count(arr):    # Traverse every array element    for num in arr:        print(prime_factors(num), end=" ")Â
# Driver Codeif __name__ == "__main__":Â Â Â Â arr = [6, 9, 12]Â Â Â Â get_factor_count(arr) |
Javascript
// JavaScript program for the above approachÂ
// A function to provide count of//distinct prime factor of a given numberfunction primeFactors(n){    //To store count of distinct prime factor of given number    let count=0;         //Boolean variable to check an element    //is included in its prime factor or not    let val=false;         // Remove all 2s that can be prime factor of n    while (n % 2 == 0)    {          val=true;        n = n/2;    }         //If 2 is included    if(val==true){count++;}      // n must be odd at this point. So we can skip    // one element (Note i = i +2)    for (let i = 3; i <= Math.sqrt(n); i = i + 2)    {        //To check whether i is included in prime factor        val=false;                 // While i divides n,divide n        while (n % i == 0)        {            val=true;            n = n/i;        }        //If i is included in prime factor        if(val==true){count++;}    }          // This condition is to handle the case when n    // is a prime number greater than 2    if (n > 2){       count++;     }      return count; }Â
// Function to get the distinct// factor count of arr[]function getFactorCount(arr, N){    //Traverse every array element    for(let i=0;i<N;i++){        document.write(primeFactors(arr[i])+ " ");    }}Â
// Driver Code    let arr = [ 6, 9, 12 ];    let N = arr.length;    getFactorCount(arr, N); |
Output-
2 1 2
Time Complexity: O(N * (√Maximum value present in array)), because O(N) in traversing the array and (√Maximum value present in array) is the maximum time to find the count of distinct prime factors of each Number
Auxiliary Space: O(1), because no extra space has been used
Efficient Approach: The above approach can be optimized by precomputing the distinct factors of all the numbers using their Smallest Prime Factors. Follow the steps below to solve the problem
- Initialize a vector, say v, to store the distinct prime factors.
- Store the Smallest Prime Factor(SPF) up to 105 using a Sieve of Eratosthenes.
- Calculate the distinct prime factors of all the numbers by dividing the numbers recursively with their smallest prime factor till it reduces to 1 and store distinct prime factors of X, in v[X].
- Traverse the array arr[] and for each array element, print the count as v[arr[i]].size().
Below is the implementation of the above approach :
C++14
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;#define MAX 100001Â
// Stores smallest prime// factor for every numberint spf[MAX];Â
// Stores distinct prime factorsvector<int> v[MAX];Â
// Function to find the smallest// prime factor of every numbervoid sieve(){    // Mark the smallest prime factor    // of every number to itself    for (int i = 1; i < MAX; i++)        spf[i] = i;Â
    // Separately mark all the    // smallest prime factor of    // every even number to be 2    for (int i = 4; i < MAX; i = i + 2)        spf[i] = 2;Â
    for (int i = 3; i * i < MAX; i++)Â
        // If i is prime        if (spf[i] == i) {Â
            // Mark spf for all numbers            // divisible by i            for (int j = i * i; j < MAX;                 j = j + i) {Â
                // Mark spf[j] if it is                // not previously marked                if (spf[j] == j)                    spf[j] = i;            }        }}Â
// Function to find the distinct// prime factorsvoid DistPrime(){Â Â Â Â for (int i = 1; i < MAX; i++) {Â
        int idx = 1;        int x = i;Â
        // Push all distinct of x        // prime factor in v[x]        if (x != 1)            v[i].push_back(spf[x]);Â
        x = x / spf[x];Â
        while (x != 1) {Â
            if (v[i][idx - 1]                != spf[x]) {Â
                // Pushback into v[i]                v[i].push_back(spf[x]);Â
                // Increment the idx                idx += 1;            }Â
            // Update x = (x / spf[x])            x = x / spf[x];        }    }}Â
// Function to get the distinct// factor count of arr[]void getFactorCount(int arr[],                    int N){    // Precompute the smallest    // Prime Factors    sieve();Â
    // For distinct prime factors    // Fill the v[] vector    DistPrime();Â
    // Count of Distinct Prime    // Factors of each array element    for (int i = 0; i < N; i++) {        cout << (int)v[arr[i]].size()             << " ";    }}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 6, 9, 12 };Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â
    getFactorCount(arr, N);Â
    return 0;} |
Java
// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*;class GFG {Â
  static int MAX = 100001;Â
  // Stores smallest prime  // factor for every number  static int spf[];Â
  // Stores distinct prime factors  static ArrayList<Integer> v[];Â
  // Function to find the smallest  // prime factor of every number  static void sieve()  {Â
    // Mark the smallest prime factor    // of every number to itself    for (int i = 1; i < MAX; i++)      spf[i] = i;Â
    // Separately mark all the    // smallest prime factor of    // every even number to be 2    for (int i = 4; i < MAX; i = i + 2)      spf[i] = 2;    for (int i = 3; i * i < MAX; i++)Â
      // If i is prime      if (spf[i] == i) {Â
        // Mark spf for all numbers        // divisible by i        for (int j = i * i; j < MAX; j = j + i) {Â
          // Mark spf[j] if it is          // not previously marked          if (spf[j] == j)            spf[j] = i;        }      }  }Â
  // Function to find the distinct  // prime factors  static void DistPrime()  {    for (int i = 1; i < MAX; i++) {Â
      int idx = 1;      int x = i;Â
      // Push all distinct of x      // prime factor in v[x]      if (x != 1)        v[i].add(spf[x]);Â
      x = x / spf[x];Â
      while (x != 1) {Â
        if (v[i].get(idx - 1) != spf[x]) {Â
          // Pushback into v[i]          v[i].add(spf[x]);Â
          // Increment the idx          idx += 1;        }Â
        // Update x = (x / spf[x])        x = x / spf[x];      }    }  }Â
  // Function to get the distinct  // factor count of arr[]  static void getFactorCount(int arr[], int N)  {Â
    // initialization    spf = new int[MAX];    v = new ArrayList[MAX];    for (int i = 0; i < MAX; i++)      v[i] = new ArrayList<>();Â
    // Precompute the smallest    // Prime Factors    sieve();Â
    // For distinct prime factors    // Fill the v[] vector    DistPrime();Â
    // Count of Distinct Prime    // Factors of each array element    for (int i = 0; i < N; i++) {      System.out.print((int)v[arr[i]].size() + " ");    }  }Â
  // Driver Code  public static void main(String[] args)  {Â
    int arr[] = { 6, 9, 12 };    int N = arr.length;Â
    getFactorCount(arr, N);  }}Â
// This code is contributed by Kingash. |
Python3
MAX = 100001Â
# Stores smallest prime# factor for every numberspf = [0] * MAXÂ
# Stores distinct prime factorsv = [[] for _ in range(MAX)]Â
# Function to find the smallest# prime factor of every numberdef sieve():Â
    # Mark the smallest prime factor    # of every number to itself    for i in range(1, MAX):        spf[i] = iÂ
    # Separately mark all the    # smallest prime factor of    # every even number to be 2    for i in range(4, MAX, 2):        spf[i] = 2    for i in range(3, int(MAX**0.5)+1):Â
        # If i is prime        if spf[i] == i:            # Mark spf for all numbers            # divisible by i            for j in range(i*i, MAX, i):                # Mark spf[j] if it is                # not previously marked                if spf[j] == j:                    spf[j] = iÂ
# Function to find the distinct# prime factorsdef DistPrime():Â Â Â Â for i in range(1, MAX):Â Â Â Â Â Â Â Â idx = 1Â Â Â Â Â Â Â Â x = iÂ
        # Push all distinct of x        # prime factor in v[x]        if x != 1:            v[i].append(spf[x])Â
        x = x // spf[x]Â
        while x != 1:            if v[i][idx-1] != spf[x]:                # Pushback into v[i]                v[i].append(spf[x])Â
                # Increment the idx                idx += 1Â
            # Update x = (x / spf[x])            x = x // spf[x]Â
# Function to get the distinct# factor count of arr[]def getFactorCount(arr, N):    # Precompute the smallest    # Prime Factors    sieve()Â
    # For distinct prime factors    # Fill the v[] vector    DistPrime()Â
    # Count of Distinct Prime    # Factors of each array element    for i in range(N):        print(len(v[arr[i]]), end=' ')Â
arr = [6, 9, 12]N = len(arr)Â
getFactorCount(arr, N)Â
# This code is contributed by phasing17. |
C#
// C# program for the above approachusing System;using System.Collections.Generic;Â
class GFG {Â
  static int MAX = 100001;Â
  // Stores smallest prime  // factor for every number  static int[] spf;Â
  // Stores distinct prime factors  static List<List<int>> v;Â
  // Function to find the smallest  // prime factor of every number  static void sieve()  {Â
    // Mark the smallest prime factor    // of every number to itself    for (int i = 1; i < MAX; i++)      spf[i] = i;Â
    // Separately mark all the    // smallest prime factor of    // every even number to be 2    for (int i = 4; i < MAX; i = i + 2)      spf[i] = 2;    for (int i = 3; i * i < MAX; i++)Â
      // If i is prime      if (spf[i] == i) {Â
        // Mark spf for all numbers        // divisible by i        for (int j = i * i; j < MAX; j = j + i) {Â
          // Mark spf[j] if it is          // not previously marked          if (spf[j] == j)            spf[j] = i;        }      }  }Â
  // Function to find the distinct  // prime factors  static void DistPrime()  {    for (int i = 1; i < MAX; i++) {Â
      int idx = 1;      int x = i;Â
      // Push all distinct of x      // prime factor in v[x]      if (x != 1)        v[i].Add(spf[x]);Â
      x = x / spf[x];Â
      while (x != 1) {Â
        if (v[i][idx - 1] != spf[x]) {Â
          // Pushback into v[i]          v[i].Add(spf[x]);Â
          // Increment the idx          idx += 1;        }Â
        // Update x = (x / spf[x])        x = x / spf[x];      }    }  }Â
  // Function to get the distinct  // factor count of arr[]  static void getFactorCount(int[] arr, int N)  {Â
    // initialization    spf = new int[MAX];    v = new List<List<int>>() ;    for (int i = 0; i < MAX; i++)      v.Add(new List<int>());Â
    // Precompute the smallest    // Prime Factors    sieve();Â
    // For distinct prime factors    // Fill the v[] vector    DistPrime();Â
    // Count of Distinct Prime    // Factors of each array element    for (int i = 0; i < N; i++) {      Console.Write((int)v[arr[i]].Count + " ");    }  }Â
  // Driver Code  public static void Main(string[] args)  {Â
    int[] arr = { 6, 9, 12 };    int N = arr.Length;Â
    getFactorCount(arr, N);  }}Â
// This code is contributed by phasing17. |
Javascript
<script>Â
    // JavaScript program for the above approach         let MAX = 100001;      // Stores smallest prime    // factor for every number    let spf;Â
    // Stores distinct prime factors    let v;Â
    // Function to find the smallest    // prime factor of every number    function sieve()    {Â
      // Mark the smallest prime factor      // of every number to itself      for (let i = 1; i < MAX; i++)        spf[i] = i;Â
      // Separately mark all the      // smallest prime factor of      // every even number to be 2      for (let i = 4; i < MAX; i = i + 2)        spf[i] = 2;      for (let i = 3; i * i < MAX; i++)Â
        // If i is prime        if (spf[i] == i) {Â
          // Mark spf for all numbers          // divisible by i          for (let j = i * i; j < MAX; j = j + i) {Â
            // Mark spf[j] if it is            // not previously marked            if (spf[j] == j)              spf[j] = i;          }        }    }Â
    // Function to find the distinct    // prime factors    function DistPrime()    {      for (let i = 1; i < MAX; i++) {Â
        let idx = 1;        let x = i;Â
        // Push all distinct of x        // prime factor in v[x]        if (x != 1)          v[i].push(spf[x]);Â
        x = parseInt(x / spf[x], 10);Â
        while (x != 1) {Â
          if (v[i][idx - 1] != spf[x]) {Â
            // Pushback into v[i]            v[i].push(spf[x]);Â
            // Increment the idx            idx += 1;          }Â
          // Update x = (x / spf[x])          x = parseInt(x / spf[x], 10);        }      }    }Â
    // Function to get the distinct    // factor count of arr[]    function getFactorCount(arr, N)    {Â
      // initialization      spf = new Array(MAX);      v = new Array(MAX);      for (let i = 0; i < MAX; i++)        v[i] = [];Â
      // Precompute the smallest      // Prime Factors      sieve();Â
      // For distinct prime factors      // Fill the v[] vector      DistPrime();Â
      // Count of Distinct Prime      // Factors of each array element      for (let i = 0; i < N; i++) {        document.write(v[arr[i]].length + " ");      }    }         let arr = [ 6, 9, 12 ];    let N = arr.length;      getFactorCount(arr, N);   </script> |
2 1 2
Time Complexity: O(N * log N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!


