Minimum removals from array to make GCD Greater in Python


Suppose we have a list of N numbers; we have to find the minimum number of removal of numbers are required so that the GCD of the remaining numbers is larger than initial GCD of N numbers.

So, if the input is like [6,9,15,30], then the output will be 2 as the initial gcd is 3, so after removing 6 and 9 we can get gcd as 15, 15 > 3.

To solve this, we will follow these steps −

  • INF := 100001
  • spf := a list with elements 0 to INF
  • Define a function sieve()
  • for i in range 4 to INF, increase by 2, do
    • spf[i] := 2
  • for i in range 3 to INF, do
    • if i^2 > INF −
      • break
    • if spf[i] is same as i, then
      • for j in range 2 * i to INF, update in each step by i, do
        • if spf[j] is same as j, then
          • spf[j] := i
  • Define a function calc_fact(). This will take x
  • ret := a new list
  • while x is not same as 1, do
    • insert spf[x] at the end of ret
    • x := x / spf[x] (get only integer part)
  • return ret
  • From the main method do the following −
  • g := 0
  • for i in range 0 to n, do
    • g := gcd(a[i], g)
  • my_map := a new map
  • for i in range 0 to n, do
    • a[i] := a[i] / g (get only integer part)
  • for i in range 0 to n, do
    • p := calc_fact(a[i])
    • s := a new map
    • for j in range 0 to size of p, do
      • s[p[j]] := 1
    • for each i in s, do
      • my_map[i] := get(i, 0) of my_map + 1
  • minimum = 10^9
  • for each i in my_map, do
    • first := i
    • second := my_map[i]
    • if (n - second) <= minimum, then
      • minimum := n - second
  • if minimum is not 10^9, then
    • return minimum
  • otherwise,
    • return -1

Example

Let us see the following implementation to get better understanding −

from math import gcd as __gcd
INF = 100001
spf = [i for i in range(INF)]
def sieve():
   for i in range(4, INF, 2):
      spf[i] = 2
   for i in range(3, INF):
      if i**2 > INF:
         break
      if (spf[i] == i):
         for j in range(2 * i, INF, i):
            if (spf[j] == j):
               spf[j] = i
def calc_fact(x):
   ret = []
   while (x != 1):
      ret.append(spf[x])
      x = x // spf[x]
   return ret
def minRemove(a, n):
   g = 0
   for i in range(n):
      g = __gcd(a[i], g)
   my_map = dict()
   for i in range(n):
      a[i] = a[i] // g
   for i in range(n):
      p = calc_fact(a[i])
      s = dict()
      for j in range(len(p)):
         s[p[j]] = 1
      for i in s:
         my_map[i] = my_map.get(i, 0) + 1
   minimum = 10**9
   for i in my_map:
      first = i
      second = my_map[i]
      if ((n - second) <= minimum):
         minimum = n - second
   if (minimum != 10**9):
      return minimum
   else:
      return -1
a = [6, 9, 15, 30]
n = len(a)
sieve()
print(minRemove(a, n))

Input

[6, 9, 15, 30], 4

Output

2

Updated on: 27-Aug-2020

91 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements