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 −
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))
[6, 9, 15, 30], 4