Find an integer X which is divisor of all except exactly one element in an array in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array of numbers; we have to find a number B which is the divisor of all except for exactly one element in the given array. We have to keep in mind that the GCD of all the elements is not 1.

So, if the input is like {8, 16, 4, 24}, then the output will be 8 as this is the divisor of all except 4.

To solve this, we will follow these steps −

  • n := size of array
  • if n is same as 1, then
    • return(array[0] + 1)
  • prefix := an array of size n, and fill with 0
  • suffix := an array of size n, and fill with 0
  • prefix[0] := array[0]
  • for i in range 1 to n, do
    • prefix[i] := gcd of (array[i] and prefix[i - 1])
  • suffix[n - 1] := array[n - 1]
  • for i in range n - 2 to -1, decrease by 1, do
    • suffix[i] := gcd of (suffix[i + 1] and array[i])
  • for i in range 0 to n + 1, do
    • cur := 0
    • if i is same as 0, then
      • cur := suffix[i + 1]
    • otherwise when i is same as n - 1, then
      • cur := prefix[i - 1]
    • otherwise,
      • cur := gcd of (prefix[i - 1] and suffix[i + 1])
    • if array[i] mod cur is not same as 0, then
      • return cur
  • return 0

Example Code 

Let us see the following implementation to get better understanding −

from math import gcd
def getDivisor(array):
   n = len(array)
   if (n == 1):
      return (array[0] + 1)
   prefix = [0] * n
   suffix = [0] * n
   prefix[0] = array[0]
   for i in range(1, n):
      prefix[i] = gcd(array[i], prefix[i - 1])
   suffix[n - 1] = array[n - 1]
   for i in range(n - 2, -1, -1):
      suffix[i] = gcd(suffix[i + 1], array[i])
   for i in range(0, n + 1):
      cur = 0
      if (i == 0):
         cur = suffix[i + 1]
      elif (i == n - 1):
         cur = prefix[i - 1]
      else:
         cur = gcd(prefix[i - 1], suffix[i + 1])
      if (array[i] % cur != 0):
         return cur
   return 0;
array = [8, 16, 4, 24]
print(getDivisor(array))

Input

[8, 16, 4, 24]

Output

8
raja
Published on 28-Aug-2020 11:55:10
Advertisements