from math import gcd
class Solution:
def countDifferentSubsequenceGCDs(self, nums):
max_num = max(nums)
nums_set = set(nums)
ans = 0
for x in range(1, max_num + 1):
g = 0
for y in range(x, max_num + 1, x):
if y in nums_set:
g = gcd(g, y)
if g == x:
break
if g == x:
ans += 1
return ans
#include <vector>
#include <unordered_set>
#include <algorithm>
using namespace std;
class Solution {
public:
int countDifferentSubsequenceGCDs(vector<int>& nums) {
int max_num = *max_element(nums.begin(), nums.end());
unordered_set<int> nums_set(nums.begin(), nums.end());
int ans = 0;
for (int x = 1; x <= max_num; ++x) {
int g = 0;
for (int y = x; y <= max_num; y += x) {
if (nums_set.count(y)) {
g = __gcd(g, y);
}
if (g == x) break;
}
if (g == x) ++ans;
}
return ans;
}
};
import java.util.*;
class Solution {
public int countDifferentSubsequenceGCDs(int[] nums) {
int maxNum = 0;
for (int n : nums) maxNum = Math.max(maxNum, n);
Set<Integer> set = new HashSet<>();
for (int n : nums) set.add(n);
int ans = 0;
for (int x = 1; x <= maxNum; x++) {
int g = 0;
for (int y = x; y <= maxNum; y += x) {
if (set.contains(y)) {
g = gcd(g, y);
}
if (g == x) break;
}
if (g == x) ans++;
}
return ans;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
var countDifferentSubsequenceGCDs = function(nums) {
const maxNum = Math.max(...nums);
const numsSet = new Set(nums);
let ans = 0;
const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
for (let x = 1; x <= maxNum; x++) {
let g = 0;
for (let y = x; y <= maxNum; y += x) {
if (numsSet.has(y)) {
g = gcd(g, y);
}
if (g === x) break;
}
if (g === x) ans++;
}
return ans;
};
nums
of positive integers. A subsequence of nums
is any sequence that can be derived from nums
by deleting some or no elements without changing the order of the remaining elements. For each possible non-empty subsequence, calculate its greatest common divisor (GCD). Your task is to count how many different GCDs can be obtained from all possible non-empty subsequences of nums
.
nums
only once and must keep their original order.nums
.
Instead, we notice that:
x
is the GCD of some subsequence, then there must exist at least two or more elements in nums
that are multiples of x
whose GCD is exactly x
.x
from 1 up to the maximum element in nums
, we can check if there is a subsequence whose GCD is x
by looking at all multiples of x
in nums
and computing their GCD.max_num
in nums
.x
from 1 to max_num
:
g = 0
to represent the running GCD.y
of x
(i.e., y = x, 2x, 3x, ...
up to max_num
):
y
is in nums
, update g = gcd(g, y)
.g
becomes equal to x
, break early (since further GCDs can't reduce it below x
).g == x
, then x
is a valid GCD for some subsequence, so increment the answer.x
can only be x
or greater, and efficiently checks each candidate.
nums = [6, 10, 3]
.
nums
. GCD(0,6)=6, GCD(6,10)=2. Now g==2, so x=2 is a possible GCD.nums
. GCD(0,3)=3, GCD(3,6)=3. So x=3 is a possible GCD.nums
. GCD(0,10)=10, which is not 5.