Skip to content

1819. Number of Different Subsequences GCDs 👍

  • Time: $O(n\log n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int countDifferentSubsequenceGCDs(vector<int>& nums) {
    const int maxNum = ranges::max(nums);
    int ans = 0;
    // factor[i] := the GCD of numbers having factor i
    vector<int> factor(maxNum + 1);

    for (const int num : nums)
      for (int i = 1; i * i <= num; ++i)
        if (num % i == 0) {
          const int j = num / i;
          factor[i] = __gcd(factor[i], num);
          factor[j] = __gcd(factor[j], num);
        }

    for (int i = 1; i <= maxNum; ++i)
      if (factor[i] == i)
        ++ans;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
  public int countDifferentSubsequenceGCDs(int[] nums) {
    final int maxNum = Arrays.stream(nums).max().getAsInt();
    int ans = 0;
    // factor[i] := the GCD of numbers having factor i
    int[] factor = new int[maxNum + 1];

    for (final int num : nums)
      for (int i = 1; i * i <= num; ++i)
        if (num % i == 0) {
          final int j = num / i;
          factor[i] = gcd(factor[i], num);
          factor[j] = gcd(factor[j], num);
        }

    for (int i = 1; i <= maxNum; ++i)
      if (factor[i] == i)
        ++ans;

    return ans;
  }

  private int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
  }
}