You are given a 0-indexed integer array nums of length n and an integer k. Return the number of index pairs (i, j) with 0 <= i < j <= n - 1 such that nums[i] * nums[j] is divisible by k, that is, nums[i] * nums[j] % k == 0.
Function Signature
def count_pairs(nums: list[int], k: int) -> int:
Rules
-
Pairs are counted by index, so equal values at different positions form separate pairs.
-
The count can reach about
5 * 10^9
, which is more than a 32-bit integer holds.
Constraints
-
1 <= len(nums) <= 10^5
-
1 <= nums[i] <= 10^5
-
1 <= k <= 10^5
Examples
Input: nums = [1, 2, 3, 4, 5], k = 2
Output: 7
A product is even exactly when the pair contains 2 or 4. Of the 10 pairs, only the 3 pairs made from the odd values 1, 3 and 5 fail, which leaves 7: (0,1), (0,3), (1,2), (1,3), (1,4), (2,3) and (3,4).
Input: nums = [1, 2, 3, 4], k = 5
Output: 0
5 is prime and none of the values is a multiple of 5, so no product is divisible by 5.
Input: nums = [4, 6, 8, 3], k = 12
Output: 4
The products are 4*6 = 24, 4*8 = 32, 4*3 = 12, 6*8 = 48, 6*3 = 18 and 8*3 = 24. Four of them are multiples of 12. 32 has no factor 3, and 18 has only one factor of 2 where 12 needs two.