Description
You are given an integer array nums.
Your task is to find the number of pairs of non-empty subsequences (seq1, seq2) of nums that satisfy the following conditions:
- The subsequences
seq1andseq2are disjoint, meaning no index ofnumsis common between them. - The GCD of the elements of
seq1is equal to the GCD of the elements ofseq2.
Return the total number of such pairs.
Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: nums = [1,2,3,4]
Output: 10
Explanation:
The subsequence pairs which have the GCD of their elements equal to 1 are:
([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])
Example 2:
Input: nums = [10,20,30]
Output: 2
Explanation:
The subsequence pairs which have the GCD of their elements equal to 10 are:
([10, 20, 30], [10, 20, 30])([10, 20, 30], [10, 20, 30])
Example 3:
Input: nums = [1,1,1,1]
Output: 50
Constraints:
1 <= nums.length <= 2001 <= nums[i] <= 200
Solutions
Couldn't think of a solution, running late for work.
Language: javascript(2026-07-14 06:58)DONE
CPU Performance71.14%
Memory Performance77.11%
/**
* @param {number[]} nums
* @return {number}
*/
var subsequencePairCount = function (nums) {
const MOD = 1_000_000_007;
const max = Math.max(...nums);
const gcd = (a, b) => {
while (b !== 0) {
[a, b] = [b, a % b];
}
return a;
};
let dp = Array.from({ length: max + 1 }, () => new Array(max + 1).fill(0));
dp[0][0] = 1;
for (const num of nums) {
const ndp = Array.from({ length: max + 1 }, () => new Array(max + 1).fill(0));
for (let j = 0; j <= max; j++) {
const divisor1 = gcd(j, num);
const dpRow = dp[j];
const ndpRow = ndp[j];
const ndpD1Row = ndp[divisor1];
for (let k = 0; k <= max; k++) {
const val = dpRow[k];
if (val === 0) continue;
const divisor2 = gcd(k, num);
ndpRow[k] = (ndpRow[k] + val) % MOD;
ndpD1Row[k] = (ndpD1Row[k] + val) % MOD;
ndpRow[divisor2] = (ndpRow[divisor2] + val) % MOD;
}
}
dp = ndp;
}
let ans = 0;
for (let j = 1; j <= max; j++) {
ans = (ans + dp[j][j]) % MOD;
}
return ans;
};