Number of Different Subsequences GCDs Problem
Description
LeetCode Problem 1819.
You are given an array nums that consists of positive integers.
The GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly.
- For example, the GCD of the sequence
[4,6,16]is2.
A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.
- For example,
[2,5,10]is a subsequence of[1,2,1,**2**,4,1,**5**,**10**].
Return the number of different GCDs among all non-empty subsequences of nums.
Example 1:

Input: nums = [6,10,3]
Output: 5
Explanation: The figure shows all the non-empty subsequences and their GCDs.
The different GCDs are 6, 10, 3, 2, and 1.
Example 2:
Input: nums = [5,15,40,5,6]
Output: 7
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 2 * 10^5
Solution
Approach: Enumerate the GCD and Its Multiples
The GCD of any subsequence is at most the largest value mx in nums, so we can test every candidate x from 1 to mx.
x is the GCD of some subsequence exactly when the GCD of all numbers in nums that are multiples of x equals x: taking more multiples can only keep the GCD the same or make it smaller down to x, and a subsequence with GCD x uses only multiples of x. So for each x, walk through its multiples y = x, 2x, 3x, ... up to mx. If y occurs in nums, fold it into a running GCD g. As soon as g == x, count x and stop.
Presence is checked with a boolean array indexed by value.
Complexity: O(n + M log M) time (the multiples of all x sum to a harmonic series) and O(M) extra space, where M is the largest value in nums.
from math import gcd
class Solution:
def countDifferentSubsequenceGCDs(self, nums: List[int]) -> int:
mx = max(nums)
vis = set(nums)
ans = 0
for x in range(1, mx + 1):
g = 0
for y in range(x, mx + 1, x):
if y in vis:
g = gcd(g, y)
if g == x:
ans += 1
break
return ans