Generate a N sized Array of unique elements with of GCD of adjacent pairs as X
Given, two integers N (always even) and X, the task is to find an array of size N with distinct numbers, such that the sum of GCD of adjacent pairs (where each element is part of only one pair) is X. If no such array is possible return -1.
Note: If there are more than 1 possible sequence return any of them
Input: N = 6, X = 6
Output: 4 8 9 10 11 12
Explanation: Starting with first two numbers, gcd of (4, 8) = 4, then gcd of (9, 10) = 1, gcd of (11, 12) = 1.
Thus, gcd sums up to 4 + 1 + 1 = 6 which is equal to X.
Input: N = 4, X = 1
Approach: The idea is that
If the value of X is less than N/2, it’s obvious that it’s not possible to make a minimum GCD of N/2.
So, if X < N/2, answer = -1.
Otherwise, lets denote extra = X – N/2 + 1, which signifies how much is the difference between X and sum (sum = the sum of GCD when all the adjacent pairs have GCD = 1 except for the first one) i.e. this must be GCD of the first pair
Thus, based upon the above fact, extra + sum of GCD of other N/2-1 pairs would be equal to X.
The formula for extra can be derived as shown below:
For N numbers there are a total of N/2 pairs.
If the first pair is left and all the other pairs are made to have a GCD of 1.
So the total sum of GCDs of these pairs are (N/2 -1)*1 = (N/2 -1)
So extra = X – (N/2 – 1) = X – N/2 + 1
Follow the steps mentioned below to solve the problem:
- Make the first pair as extra and (extra*2).
- Make the other pairs made up of consecutive integers such that they have GCD = 1.
Below is the implementation of the above approach:
2 4 5 6 7
Time complexity: O(N)
Space complexity: O(1)