![]() |
VOOZH | about |
Given an array arr[] of N integers, the task is to find an integer X such that the integers that are divisible by X and the integers that are not divisible by X are alternative to each other in the array. If there is no such value print -1.
Examples:
Input: arr[] = {6, 5, 9, 10, 12, 15}
Output : 5
Explanation: The x = 5 divides all the elements at odd indices (0 based indexing)
but doesn't divide the elements at even indices so the answer is 5.Input: {10, 20, 40, 30}
Output: -1
Approach: The approach is based on GCD since one set of alternating elements whether at odd indices or even indices should be completely divisible by an integer the only number that divides all the numbers is the GCD of that set of elements. The GCD of one set should not be equal to that of the other set then only that GCD becomes the answer. Follow the steps below to solve this problem:
Below is the implementation of the above approach.
5
Time Complexity: O(N)
Auxiliary Space: O(1)