Difficulty : Easy
Pre-requisites : Greedy, Prime factorisation
Problem : You are given an array of integers, anytime you can pick two numbers from it and divide them both by some common factor of them. Your goal is to find the minimal possible product of the numbers of an array after performing a number of such operations.
Let’s decompose each number into the product of primes, that is, let’s find it’s factorisation.
We know that Ai is not greater than 109. So, if there is a prime factor that is greater than, say 40000 (virtually, greater than the square root of 109), it will appear only once in the decomposition. So, each prime number greater than 40000 will appear in the final product of the array elements no more than once. Each number from the array may or may not have this prime factor in its prime decomposition but if it has, this prime factor will appear only once in this number’s decomposition. So, for each prime divisor greater than 40000 if it appears in the even number of the array elements, then it is possible to split the numbers that have this divisor into pairs and to get rid of it completely. If it appears in the odd number of the array elements, then we can pair up all but one numbers that have this factor in their prime decomposition. So, it will appear once in the final product in the array elements.
For the rest of prime numbers, that is, those that are smaller than 40000, we can solve the problem separately, and the solution here is a greedy one:
- For each prime factor let’s write out the list of occurences in every array element.
- Then, delete all zeroes from this list.
- Anytime we will pick two maximal numbers from the list and decrease them by one. That corresponds to divising some two numbers for this prime factor.
- If after the desreasing some elements became zeroes, we just throw them away.
- When there remains only one number (nonzero one), we stop our algo.
In order to pick two maximal numbers and to change them we can use the STL priority queue. But there is also an alternative to store something like the amount of every list’s number occurences in the array, like Amount[X] the number of X’s in the list. That makes the implementation easier for Pascal coders.