Problem Description
Description
985 has n positive integers, and he wants to know how many different factor pairs (a[i], a[j]) exist such that
1 <= i, j <= n && i != j && a[j] % a[i] == 0, where i and j are the indices of the elements.
In particular, he considers (a[i], a[j]) and (a[j], a[i]) to be the same factor pair.
Input
The first line contains an integer t, representing t test cases.
Each test case occupies two lines: the first line contains an n representing the number of elements, and the next line contains n integers a[].
Note: 1 <= t <= 30, 1 <= n <= 1e5, 1 <= a[] <= 1e6.
Output
An integer representing the final answer.
Sample Input
| |
Sample Output
| |
Problem Analysis
Obviously, a direct $n^2$ approach will TLE.
Yu Shen:
This problem is equivalent to finding the sum of the number of factors of all numbers, but note that (a[i], a[i]) is invalid.
Here let’s first describe a relatively straightforward idea:
First, we can sort in ascending order and deduplicate. Use num[i] to record the number of occurrences of element i, and sum[i] to represent the number of factors of element i, excluding i itself.
When counting a[i], its contribution is: sum[a[i]] * num[a[i]] + num[i] * (num[i] - 1) / 2.
Consider processing from front to back. When counting a[i], we can count the multiples of a[i], a[i] * j, i.e., sum[a[i] * j] += num[a[i]] (j >= 2).
In this way, when computing the contribution of a[i], the value of sum[a[i]] has already been computed, so we only need to accumulate the contribution, and the time complexity is on the order of the harmonic series.
Time complexity: O(T * n * log(n)). Actually, we can first preprocess with something like the Prime Sieve, which would be faster.
Rookie:
Consider the effect of each number on its multiples.
Adopt an approach similar to the Prime Sieve.
Each time we encounter a number t,
add the count of t to all multiples of t.
So add (count of t * count of this multiple of t) to the result.
Because t itself is also a factor of itself,
so we need res+=n*(n-1)/2.
| |
Problem address:ZZULI 1902 985’s Factor Pair Problem