Find Number of Different Subsequences GCDs in Python



Suppose we have an array nums with positive values. We have to find the number of different GCDs among all non-empty subsequences of nums. As we know the GCD of a sequence of numbers is the greatest value that divides all the numbers in the sequence evenly.

So, if the input is like nums = [4,6,18], then the output will be 4 because gcd([4]) = 4, gcd([6]) = 6, gcd([18]) = 18 gcd([4,6]) = 2, gcd([4,18]) = 2, gcd([6,18]) = 6, gcd([4,6,18]) = 2 so all numbers are [4,6,18,2], there are 4 numbers.

To solve this, we will follow these steps −

  • T := maximum of nums + 1

  • nums := a new set containing all distinct numbers of nums

  • ans := 0

  • for x in range 1 to T - 1, do

    • g := 0

    • for y in range x to T - 1, update in each step by x, do

      • if y is in nums, then

        • g := gcd(g, y)

      • if g is same as x, then

        • come out from loops

    • if g is same as x, then

      • ans := ans + 1

  • return ans

Example

Let us see the following implementation to get better understanding

from math import gcd
def solve(nums):
   T = max(nums) + 1
   nums = set(nums)
   ans = 0

   for x in range(1, T):
      g = 0
      for y in range(x, T, x):
         if y in nums:
            g = gcd(g, y)
         if g == x:
            break

      if g == x:
         ans += 1

   return ans

nums = [4,6,18]
print(solve(nums))

Input

[4,6,18]

Output

4
Updated on: 2021-10-08T08:08:56+05:30

170 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements