![]() |
VOOZH | about |
Given an array of N elements, find the minimum number of insertions to convert the given array into a co-prime array. Print the resultant array also.
Co-prime Array : An array in which every pair of adjacent elements are co-primes. i.e, .
Examples :
Input : A[] = {2, 7, 28}
Output : 1
Explanation :
Here, 1st pair = {2, 7} are co-primes( gcd(2, 7) = 1).
2nd pair = {7, 28} are not co-primes, insert 9
between them. gcd(7, 9) = 1 and gcd(9, 28) = 1.Input : A[] = {5, 10, 20}
Output : 2
Explanation :
Here, there is no pair which are co-primes.
Insert 7 between (5, 10) and 1 between (10, 20).
Observe that to make a pair to become co-primes we have to insert a number which makes the newly formed pairs co-primes. So, we have to check every adjacent pair for their co-primality and insert a number if required. Now, what is the number that should be inserted? Let us take two numbers a and b. If any of a or b is 1, then GCD(a, b) = 1. So, we can insert ONE(1) at every pair. For efficiency we use euler's gcd function .
Below is the implementation of the above approach:
2 5 1 10 1 20
Time Complexity: O(n log(Ai)), for using __gcd function
Auxiliary Space: O(1)