Problem Description
Given an array of positive integers, return the number of distinct greatest common divisors (GCDs) that can be obtained from all non-empty subsequences of the array.
Key Insights
- The number of subsequences is too large to enumerate, so instead consider candidates for the GCD.
- For each candidate d, if it divides some elements, then check if there exists a subsequence whose GCD is exactly d.
- By iterating over the multiples of d and computing their GCD, we can determine if d is achievable.
- Use a frequency array to quickly check the presence of numbers and optimize the multiple iterations.
Space and Time Complexity
Time Complexity: O(max(nums) * log(max(nums))) (The inner loop iterates over multiples, leading to a harmonic sum complexity.) Space Complexity: O(max(nums)) (For the frequency array.)
Solution
The solution first builds a frequency table for all numbers in the array up to the maximum value. Then, for each potential GCD candidate d from 1 to max(nums), iterate through its multiples. For each multiple present in the array, update a running GCD value. If the running GCD becomes equal to d, then d is a valid GCD that can be obtained from some subsequence, so increment the count. This leverages the arithmetic properties of the GCD and avoids exploring all possible subsequences.