Number of Different Subsequences GCDs — LeetCode 1819 Python Solution
- Problem
- #1819
- Pattern
- Math and Number Theory
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- nums = [6,10,3]
- Output
- 5
- Explanation
- The figure shows all the non-empty subsequences and their GCDs.
Python solution
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n + M \times \log M) |
| Space | O(M) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1819. Number of Different Subsequences GCDs is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Number Theory.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1819. Number of Different Subsequences GCDs?
- LeetCode 1819. Number of Different Subsequences GCDs is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1819. Number of Different Subsequences GCDs?
- The Python solution on this page runs in O(n + M \times \log M).
- What is the space complexity of LeetCode 1819. Number of Different Subsequences GCDs?
- The Python solution on this page uses O(M) auxiliary space.
- What topics does LeetCode 1819. Number of Different Subsequences GCDs cover?
- LeetCode 1819. Number of Different Subsequences GCDs is tagged Array, Math, Counting and Number Theory on LeetCode.