Given an array B[] of size N, the duty is to print an array A[] such that for each ith aspect B[i] is gcd of the primary i components of A[] i.e. Bi = gcd (A1, A2, …., Ai) and if no such array A[] exists, print −1.
Examples:
Enter: B = {4, 2}
Output: 4 2
Clarification: One attainable reply is [4, 2] as a result of
B may be generated as follows: B=[gcd(4), gcd(4, 2)]=[4, 2].Enter: B = {2, 6, 8, 10}
Output: -1
Clarification: No array exists which satisfies the given situation.
Method: The issue may be solved based mostly on the next remark:
- We all know that Bi = gcd(A1, A2, . . . , Ai) and Bi+1 = gcd(A1, A2, . . ., Ai, Ai+1) = gcd(gcd(A1, A2, . . ., Ai), Ai+1) = gcd(Bi, Ai+1). This fashion, we will write Bi+1 = gcd(Bi , Ai+1).
- The implication of that is that Bi+1 have to be an element of Bi , Since gcd of two numbers is divisor of each numbers. Therefore, situation Bi+1 divides Bi ought to maintain for all 1 ≤ i <N.
- So if the given array has any such i the place Bi+1 doesn’t divide Bi , no such A can exist.
- The given array B is a sound candidate for A as Bi+1 = gcd(Bi, Ai+1), however we’ve got Ai+1 = Bi+1 . Since Bi+1 divide Bi , gcd(Bi, Bi+1) = Bi+1. So the given array B satisfies our situation and may be printed as array A.
Observe the beneath steps to unravel the issue:
- Initialize a boolean variable flag = true.
- Iterate on the given array and verify the next:
- If the subsequent aspect shouldn’t be an element of the present aspect:
- Set flag = false.
- Terminate the loop.
- If the subsequent aspect shouldn’t be an element of the present aspect:
- If the flag is true:
- Print the given array B[].
- else print -1.
Under is the implementation of the above strategy.
Java
|
Time Complexity: O(N) for traversing the given array.
Auxiliary Area: O(1) as fixed house is used.