Given an array arr[] consisting of positive integers and an integer K, the task is to find the minimum number of operations required to make the product of all elements of the array divisible by K where in one operation you can select any prime number and insert it into the array.
Examples:
Input: arr[] = {6, 7, 8, 9, 3}, K = 15 Output: 1 Explanation: The product of the array is 9072. Add 5 to the array now the product becomes 45360 which is exactly divisible by 15.
Input: arr[] = {4, 8, 19, 23}, K = 66 Output: 2 Explanation: Insert 3 and 11 into the array and the product of the final array becomes divisible by 66. It is guaranteed that at least 2 operations are required.
Approach: To solve the problem follow the below idea and observations:
Observations:
- The elementary intuition suggests taking the product of all array elements and dividing it by K. Whatever the number obtained (say Y), we need to find the number of primes occurring in its prime factorization. But the issue is that the product of all elements may go beyond the maximum value of integer datatypes i.e. 1018.
- However, another noteworthy point is that we don’t need to calculate the product of the array as we are only concerned with the prime factorization of the number obtained upon the division of the array product by X.
This observation leads to the following approach:
If a number A divides another number B then the following shall always be true:
- All the prime factors of A should be present in prime factorization of B.
- For each prime factor of A, It’s number of occurrences in prime factorization of B should be greater than equal to it’s number of occurrences in prime factorization of A.
- The problem statement can be related to the above idea. K is equivalent to A and B is equivalent to the array product. In spite of calculating the product of all elements of the array, for each individual element of the array count the frequency (number of occurrences) of each prime factor occurring in its calculation.
- When a case happens such that the frequency of a prime number num is greater in K (say p) than in array product (say q) we need to insert num into the main array (p-q) times.
Follow the below-mentioned steps to solve the problem:
- Calculate the frequency of the prime factors of all elements of the main array arr[] and store it in a map mp1.
- In other words, mp1 stores the product of the whole array in the form of prime factors. Each key-value pair represents a prime factor of the array product with its frequency.
- Perform a similar calculation for the number K and store all prime factors and their number of occurrences in another map mp2.
- Now for each element of mp2 evaluate the prime numbers whose frequency is greater in mp2 as compared to mp1. Add the difference of frequencies to the answer.
- Return the answer
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > prime_factors( int num)
{
vector< int > res;
while (num % 2 == 0) {
res.push_back(2);
num /= 2;
}
for ( int i = 3; i * i <= num; i += 2) {
while (num % i == 0) {
res.push_back(i);
num /= i;
}
}
if (num > 1) {
res.push_back(num);
}
return res;
}
int solve( int arr[], int n, int X)
{
unordered_map< int , int > mp1;
vector< int > cnt;
for ( int i = 0; i < n; i++) {
cnt = prime_factors(arr[i]);
for ( int j = 0; j < cnt.size(); j++) {
mp1[cnt[j]]++;
}
cnt.clear();
}
vector< int > res = prime_factors(X);
unordered_map< int , int > mp2;
for ( int i = 0; i < res.size(); i++) {
mp2[res[i]]++;
}
int ans = 0;
for ( auto it = mp2.begin(); it != mp2.end(); ++it) {
if (it->second > mp1[it->first]) {
ans += (it->second - mp1[it->first]);
}
}
return ans;
}
int main()
{
int arr[] = { 6, 4, 3 };
int N = sizeof (arr) / sizeof (arr[0]);
int X = 35;
int arr2[] = { 6, 7, 8, 9, 3 };
int M = sizeof (arr2) / sizeof (arr2[0]);
int Y = 15;
int arr3[] = { 4, 8, 19, 23 };
int O = sizeof (arr3) / sizeof (arr3[0]);
int Z = 66;
cout << solve(arr, N, X) << endl;
cout << solve(arr2, M, Y) << endl;
cout << solve(arr3, O, Z) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG {
static Vector<Integer> prime_factors( int num)
{
Vector<Integer> res = new Vector<Integer>();
while (num % 2 == 0 ) {
res.add( 2 );
num /= 2 ;
}
for ( int i = 3 ; i * i <= num; i += 2 ) {
while (num % i == 0 ) {
res.add(i);
num /= i;
}
}
if (num > 1 ) {
res.add(num);
}
return res;
}
static int solve( int arr[], int n, int X)
{
HashMap<Integer, Integer> mp1 = new HashMap<Integer, Integer>();
Vector<Integer> cnt;
for ( int i = 0 ; i < n; i++) {
cnt = prime_factors(arr[i]);
for ( int j = 0 ; j < cnt.size(); j++) {
mp1.put(cnt.get(j), mp1.getOrDefault(cnt.get(j), 0 ) + 1 );
}
cnt.clear();
}
Vector<Integer> res = prime_factors(X);
HashMap<Integer, Integer> mp2 = new HashMap<Integer, Integer>();
for ( int i = 0 ; i < res.size(); i++) {
mp2.put(res.get(i), mp2.getOrDefault(res.get(i), 0 ) + 1 );
}
int ans = 0 ;
for (Map.Entry<Integer, Integer> entry : mp2.entrySet()) {
if (entry.getValue() > mp1.getOrDefault(entry.getKey(), 0 )) {
ans += (entry.getValue() - mp1.getOrDefault(entry.getKey(), 0 ));
}
}
return ans;
}
public static void main(String[] args)
{
int arr[] = { 6 , 4 , 3 };
int N = arr.length;
int X = 35 ;
int arr2[] = { 6 , 7 , 8 , 9 , 3 };
int M = arr2.length;
int Y = 15 ;
int arr3[] = { 4 , 8 , 19 , 23 };
int O = arr3.length;
int Z = 66 ;
System.out.println(solve(arr,N,X));
System.out.println(solve(arr2,M,Y));
System.out.println(solve(arr3,O,Z));
}
}
|
Python3
from typing import List
def prime_factors(num: int ) - > List [ int ]:
factors = []
while num % 2 = = 0 :
factors.append( 2 )
num = num / / 2
for i in range ( 3 , int (num * * 0.5 ) + 1 , 2 ):
while num % i = = 0 :
factors.append(i)
num = num / / i
if num > 2 :
factors.append(num)
return factors
def solve(arr: List [ int ], n: int , X: int ) - > int :
factors_count = {}
for i in range (n):
factors = prime_factors(arr[i])
for factor in factors:
if factor in factors_count:
factors_count[factor] + = 1
else :
factors_count[factor] = 1
X_factors = prime_factors(X)
X_factors_count = {}
for factor in X_factors:
if factor in X_factors_count:
X_factors_count[factor] + = 1
else :
X_factors_count[factor] = 1
ans = 0
for factor in X_factors_count:
if factor not in factors_count or X_factors_count[factor] > factors_count[factor]:
ans + = X_factors_count[factor] - factors_count.get(factor, 0 )
return ans
arr = [ 6 , 4 , 3 ]
N = len (arr)
X = 35
print (solve(arr,N,X))
arr2 = [ 6 , 7 , 8 , 9 , 3 ]
M = len (arr2)
Y = 15
print (solve(arr2,M,Y))
arr3 = [ 4 , 8 , 19 , 23 ]
O = len (arr3)
Z = 66
print (solve(arr3,O,Z))
|
Javascript
function primeFactors(num) {
let factors = [];
while (num % 2 === 0) {
factors.push(2);
num = num / 2;
}
for (let i = 3; i <= Math.sqrt(num); i += 2) {
while (num % i === 0) {
factors.push(i);
num = num / i;
}
}
if (num > 2) {
factors.push(num);
}
return factors;
}
function solve(arr, n, X) {
let factorsCount = {};
for (let i = 0; i < n; i++) {
let factors = primeFactors(arr[i]);
for (let factor of factors) {
if (factorsCount[factor]) {
factorsCount[factor]++;
} else {
factorsCount[factor] = 1;
}
}
}
let XFactors = primeFactors(X);
let XFactorsCount = {};
for (let factor of XFactors) {
if (XFactorsCount[factor]) {
XFactorsCount[factor]++;
} else {
XFactorsCount[factor] = 1;
}
}
let ans = 0;
for (let factor in XFactorsCount) {
if (!factorsCount[factor] || XFactorsCount[factor] > factorsCount[factor]) {
ans += XFactorsCount[factor] - (factorsCount[factor] || 0);
}
}
return ans;
}
let arr = [6, 4, 3];
let N = arr.length;
let X = 35;
console.log(solve(arr, N, X));
let arr2 = [6, 7, 8, 9, 3];
let M = arr2.length;
let Y = 15;
console.log(solve(arr2, M, Y));
let arr3 = [4, 8, 19, 23];
let O = arr3.length;
let Z = 66;
console.log(solve(arr3, O, Z));
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class MainClass {
public static List< int > prime_factors( int num)
{
List< int > res = new List< int >();
while (num % 2 == 0) {
res.Add(2);
num /= 2;
}
for ( int i = 3; i * i <= num; i += 2) {
while (num % i == 0) {
res.Add(i);
num /= i;
}
}
if (num > 1) {
res.Add(num);
}
return res;
}
public static int solve( int [] arr, int n, int X)
{
Dictionary< int , int > mp1 = new Dictionary< int , int >();
List< int > cnt;
for ( int i = 0; i < n; i++) {
cnt = prime_factors(arr[i]);
for ( int j = 0; j < cnt.Count; j++) {
if (mp1.ContainsKey(cnt[j])) {
mp1[cnt[j]]++;
} else {
mp1.Add(cnt[j], 1);
}
}
cnt.Clear();
}
List< int > res = prime_factors(X);
Dictionary< int , int > mp2 = new Dictionary< int , int >();
for ( int i = 0; i < res.Count; i++) {
if (mp2.ContainsKey(res[i])) {
mp2[res[i]]++;
} else {
mp2.Add(res[i], 1);
}
}
int ans = 0;
foreach ( var item in mp2) {
if (item.Value > mp1[item.Key]) {
ans += (item.Value - mp1[item.Key]);
}
}
return ans;
}
public static void Main( string [] args) {
int [] arr = { 6, 4, 3 };
int N = arr.Length;
int X = 35;
int [] arr2 = { 6, 7, 8, 9, 3 };
int M = arr2.Length;
int Y = 15;
int [] arr3 = { 4, 8, 19, 23 };
int O = arr3.Length;
int Z = 66;
Console.WriteLine(solve(arr, N, X));
Console.WriteLine(solve(arr2, M, Y));
Console.WriteLine(solve(arr3, O, Z));
}
|
Time Complexity : O(N*sqrt(N)) Auxiliary Space : O(N)
|