Problem Description
Given a list of queries where each query is represented as [n, k], the goal is to count the number of ways to fill an array of size n with positive integers such that the product of the elements equals k. Since these counts can be very large, the answer for each query should be returned modulo 10^9+7.
Key Insights
- The problem can be reduced to a combinatorial one by factorizing k into its prime factors.
- For each prime factor p with exponent e in the factorization of k, we need to distribute e occurrences among n numbers. This is equivalent to finding the number of nonnegative integer solutions to a1 + a2 + … + an = e, which equals C(e + n – 1, n – 1) (stars and bars theorem).
- The final answer for a query is the product (over all prime factors) of the combinations computed for each prime factor.
- Precomputation of factorials and modular inverses (using Fermat’s little theorem, as the modulus is prime) will be used to efficiently compute binomial coefficients.
- Factorizing k has a worst-case complexity of about O(√k), which is acceptable given the constraints.
Space and Time Complexity
Time Complexity: O(Q * √k + P) where Q is the number of queries (up to 10^4), k is at most 10^4, and P is the cost for precomputing factorials (precompute up to around 20000). Space Complexity: O(max_factorial_value) for storing factorials and modular inverses, which is roughly O(20000).
Solution
The solution first precomputes the necessary factorials and their modular inverses up to a predefined maximum (ensuring it covers the maximum possible value for n + exponent). For each query, the number k is factorized, and for each factor with exponent e, the number of distributions among n numbers is computed using the combination formula: C(n + e - 1, n - 1). The overall result for the query is the product of these combination values (taken modulo 10^9+7). This approach leverages stars and bars (combinatorial distribution) and modular arithmetic to handle the large numbers.