Count Ways to Make Array With Product Problem
Description
LeetCode Problem 1735.
You are given a 2D integer array, queries. For each queries[i], where queries[i] = [n_i, k_i], find the number of different ways you can place positive integers into an array of size n_i such that the product of the integers is k_i. As the number of ways may be too large, the answer to the i^th query is the number of ways modulo 10^9 + 7.
Return an integer array answer where answer.length == queries.length, and answer[i] is the answer to the i^th query.
Example 1:
Input: queries = [[2,6],[5,1],[73,660]]
Output: [4,1,50734910]
Explanation: Each query is independent.
[2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1].
[5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1].
[73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 10^9 + 7 = 50734910.
Example 2:
Input: queries = [[1,1],[2,2],[3,3],[4,4],[5,5]]
Output: [1,2,3,10,5]
Constraints:
1 <= queries.length <= 10^41 <= n_i, k_i <= 10^4
Solution
Approach: Prime Factorization + Combinatorics
Factor k = p1^x1 * p2^x2 * ... * pm^xm. Each prime is spread over the n array positions independently, and an exponent of 0 at a position is allowed. So the answer is the product, over the primes, of the number of ways to distribute x identical items into n boxes where boxes may be empty.
By stars and bars that number is C(x + n - 1, n - 1). So for each query we factor k, compute these binomials and multiply them modulo 10^9 + 7.
To compute binomials fast, precompute factorials and their modular inverses once (the largest argument is about n + 13, since k <= 10^4 has exponents at most 13).
Complexity: about O(sqrt(k)) per query for the factorization, plus O(N) precomputation.
from collections import defaultdict
N = 10020
MOD = 10**9 + 7
f = [1] * N
g = [1] * N
p = defaultdict(list)
for i in range(1, N):
f[i] = f[i - 1] * i % MOD
g[i] = pow(f[i], MOD - 2, MOD)
x = i
j = 2
while j <= x // j:
if x % j == 0:
cnt = 0
while x % j == 0:
cnt += 1
x //= j
p[i].append(cnt)
j += 1
if x > 1:
p[i].append(1)
def comb(n, k):
return f[n] * g[k] * g[n - k] % MOD
class Solution:
def waysToFillArray(self, queries: List[List[int]]) -> List[int]:
ans = []
for n, k in queries:
t = 1
for x in p[k]:
t = t * comb(x + n - 1, n - 1) % MOD
ans.append(t)
return ans