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++
#include <bits/stdc++.h>
using namespace std;
int primeFactors( int n)
{
int count=0;
bool val= false ;
while (n % 2 == 0)
{
val= true ;
n = n/2;
}
if (val== true ){count++;}
for ( int i = 3; i <= sqrt (n); i = i + 2)
{
val= false ;
while (n % i == 0)
{
val= true ;
n = n/i;
}
if (val== true ){count++;}
}
if (n > 2){
count++;
}
return count;
}
void getFactorCount( int arr[],
int N)
{
for ( int i=0;i<N;i++){
cout<<primeFactors(arr[i])<< " " ;
}
}
int 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 {
static int primeFactors( int n) {
int count = 0 ;
boolean val = false ;
while (n % 2 == 0 ) {
val = true ;
n = n / 2 ;
}
if (val) {
count++;
}
for ( int i = 3 ; i <= Math.sqrt(n); i = i + 2 ) {
val = false ;
while (n % i == 0 ) {
val = true ;
n = n / i;
}
if (val) {
count++;
}
}
if (n > 2 ) {
count++;
}
return count;
}
static void getFactorCount( int [] arr, int N) {
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
def prime_factors(n):
count = 0
val = False
while n % 2 = = 0 :
val = True
n = n / / 2
if val = = True :
count + = 1
for i in range ( 3 , int (math.sqrt(n)) + 1 , 2 ):
val = False
while n % i = = 0 :
val = True
n = n / / i
if val = = True :
count + = 1
if n > 2 :
count + = 1
return count
def get_factor_count(arr):
for num in arr:
print (prime_factors(num), end = " " )
if __name__ = = "__main__" :
arr = [ 6 , 9 , 12 ]
get_factor_count(arr)
|
C#
using System;
class Program
{
static int PrimeFactors( int n)
{
int count = 0;
bool val = false ;
while (n % 2 == 0)
{
val = true ;
n = n / 2;
}
if (val)
{
count++;
}
for ( int i = 3; i <= Math.Sqrt(n); i += 2)
{
val = false ;
while (n % i == 0)
{
val = true ;
n = n / i;
}
if (val)
{
count++;
}
}
if (n > 2)
{
count++;
}
return count;
}
static void GetFactorCount( int [] arr)
{
foreach ( int num in arr)
{
Console.Write(PrimeFactors(num) + " " );
}
}
static void Main()
{
int [] arr = { 6, 9, 12 };
GetFactorCount(arr);
}
}
|
Javascript
function primeFactors(n)
{
let count=0;
let val= false ;
while (n % 2 == 0)
{
val= true ;
n = n/2;
}
if (val== true ){count++;}
for (let i = 3; i <= Math.sqrt(n); i = i + 2)
{
val= false ;
while (n % i == 0)
{
val= true ;
n = n/i;
}
if (val== true ){count++;}
}
if (n > 2){
count++;
}
return count;
}
function getFactorCount(arr, N)
{
for (let i=0;i<N;i++){
document.write(primeFactors(arr[i])+ " " );
}
}
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
#include <bits/stdc++.h>
using namespace std;
#define MAX 100001
int spf[MAX];
vector< int > v[MAX];
void sieve()
{
for ( int i = 1; i < MAX; i++)
spf[i] = i;
for ( int i = 4; i < MAX; i = i + 2)
spf[i] = 2;
for ( int i = 3; i * i < MAX; i++)
if (spf[i] == i) {
for ( int j = i * i; j < MAX;
j = j + i) {
if (spf[j] == j)
spf[j] = i;
}
}
}
void DistPrime()
{
for ( int i = 1; i < MAX; i++) {
int idx = 1;
int x = i;
if (x != 1)
v[i].push_back(spf[x]);
x = x / spf[x];
while (x != 1) {
if (v[i][idx - 1]
!= spf[x]) {
v[i].push_back(spf[x]);
idx += 1;
}
x = x / spf[x];
}
}
}
void getFactorCount( int arr[],
int N)
{
sieve();
DistPrime();
for ( int i = 0; i < N; i++) {
cout << ( int )v[arr[i]].size()
<< " " ;
}
}
int main()
{
int arr[] = { 6, 9, 12 };
int N = sizeof (arr) / sizeof (arr[0]);
getFactorCount(arr, N);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG
{
static int MAX = 100001 ;
static int spf[];
static ArrayList<Integer> v[];
static void sieve()
{
for ( int i = 1 ; i < MAX; i++)
spf[i] = i;
for ( int i = 4 ; i < MAX; i = i + 2 )
spf[i] = 2 ;
for ( int i = 3 ; i * i < MAX; i++)
if (spf[i] == i) {
for ( int j = i * i; j < MAX; j = j + i) {
if (spf[j] == j)
spf[j] = i;
}
}
}
static void DistPrime()
{
for ( int i = 1 ; i < MAX; i++) {
int idx = 1 ;
int x = i;
if (x != 1 )
v[i].add(spf[x]);
x = x / spf[x];
while (x != 1 ) {
if (v[i].get(idx - 1 ) != spf[x]) {
v[i].add(spf[x]);
idx += 1 ;
}
x = x / spf[x];
}
}
}
static void getFactorCount( int arr[], int N)
{
spf = new int [MAX];
v = new ArrayList[MAX];
for ( int i = 0 ; i < MAX; i++)
v[i] = new ArrayList<>();
sieve();
DistPrime();
for ( int i = 0 ; i < N; i++) {
System.out.print(( int )v[arr[i]].size() + " " );
}
}
public static void main(String[] args)
{
int arr[] = { 6 , 9 , 12 };
int N = arr.length;
getFactorCount(arr, N);
}
}
|
Python3
MAX = 100001
spf = [ 0 ] * MAX
v = [[] for _ in range ( MAX )]
def sieve():
for i in range ( 1 , MAX ):
spf[i] = i
for i in range ( 4 , MAX , 2 ):
spf[i] = 2
for i in range ( 3 , int ( MAX * * 0.5 ) + 1 ):
if spf[i] = = i:
for j in range (i * i, MAX , i):
if spf[j] = = j:
spf[j] = i
def DistPrime():
for i in range ( 1 , MAX ):
idx = 1
x = i
if x ! = 1 :
v[i].append(spf[x])
x = x / / spf[x]
while x ! = 1 :
if v[i][idx - 1 ] ! = spf[x]:
v[i].append(spf[x])
idx + = 1
x = x / / spf[x]
def getFactorCount(arr, N):
sieve()
DistPrime()
for i in range (N):
print ( len (v[arr[i]]), end = ' ' )
arr = [ 6 , 9 , 12 ]
N = len (arr)
getFactorCount(arr, N)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int MAX = 100001;
static int [] spf;
static List<List< int >> v;
static void sieve()
{
for ( int i = 1; i < MAX; i++)
spf[i] = i;
for ( int i = 4; i < MAX; i = i + 2)
spf[i] = 2;
for ( int i = 3; i * i < MAX; i++)
if (spf[i] == i) {
for ( int j = i * i; j < MAX; j = j + i) {
if (spf[j] == j)
spf[j] = i;
}
}
}
static void DistPrime()
{
for ( int i = 1; i < MAX; i++) {
int idx = 1;
int x = i;
if (x != 1)
v[i].Add(spf[x]);
x = x / spf[x];
while (x != 1) {
if (v[i][idx - 1] != spf[x]) {
v[i].Add(spf[x]);
idx += 1;
}
x = x / spf[x];
}
}
}
static void getFactorCount( int [] arr, int N)
{
spf = new int [MAX];
v = new List<List< int >>() ;
for ( int i = 0; i < MAX; i++)
v.Add( new List< int >());
sieve();
DistPrime();
for ( int i = 0; i < N; i++) {
Console.Write(( int )v[arr[i]].Count + " " );
}
}
public static void Main( string [] args)
{
int [] arr = { 6, 9, 12 };
int N = arr.Length;
getFactorCount(arr, N);
}
}
|
Javascript
<script>
let MAX = 100001;
let spf;
let v;
function sieve()
{
for (let i = 1; i < MAX; i++)
spf[i] = i;
for (let i = 4; i < MAX; i = i + 2)
spf[i] = 2;
for (let i = 3; i * i < MAX; i++)
if (spf[i] == i) {
for (let j = i * i; j < MAX; j = j + i) {
if (spf[j] == j)
spf[j] = i;
}
}
}
function DistPrime()
{
for (let i = 1; i < MAX; i++) {
let idx = 1;
let x = i;
if (x != 1)
v[i].push(spf[x]);
x = parseInt(x / spf[x], 10);
while (x != 1) {
if (v[i][idx - 1] != spf[x]) {
v[i].push(spf[x]);
idx += 1;
}
x = parseInt(x / spf[x], 10);
}
}
}
function getFactorCount(arr, N)
{
spf = new Array(MAX);
v = new Array(MAX);
for (let i = 0; i < MAX; i++)
v[i] = [];
sieve();
DistPrime();
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>
|
Time Complexity: O(N * log N)
Auxiliary Space: O(N)
Last Updated :
02 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...