VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-x-such-that-elements-at-only-alternate-indices-in-given-array-are-divisible-by-x/

⇱ Find X such that elements at only alternate indices in given Array are divisible by X - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find X such that elements at only alternate indices in given Array are divisible by X

Last Updated : 23 Jul, 2025

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:

  • Traverse the array arr[] and calculate the GCD of the elements at odd indices (gcd1) and elements at even indices (gcd2) separately.
  • If both the GCDs are not equal then do the following:
    • Check if there is an integer in even indices that is divisible by gcd1. If any such integer found then gcd1 is not the required value.
    • Check if there is an integer in odd indices that is divisible by gcd2. If any such integer found then gcd2 is not the required value.
    • If any of the above two conditions is false, the corresponding GCD value is the answer. Else no such X exists.
  • Otherwise no such X is possible.

Below is the implementation of the above approach.


Output
5

Time Complexity: O(N)
Auxiliary Space: O(1)


 

Comment