We should have . It is clear that each can have only have as its prime factor, although the multiplicity of the exponent might differ. However, their product should contain exactly multiplicity.
So, let’s assume that . Then, we should have
So we are looking for the number of non-negative solution to:
From Stars and Bars, the number of distinct solution is equal to . If you are not familiar with Stars and Bars, you can read about it here but don’t read too much into it, else you’d end up confusing yourself. For a long time, I was afraid of problems that involved Stars and Bars, mainly because I used to apply Stars and Bars combinatorics from scratch for each problem.
But if you take the combinatorics for granted, and just memorize the formula for
is , you will be able to solve all problems that involve Stars and Bars. Why? Because there’s a bijection between them, and every problem that can be solved using Stars and Bars can also be reduced to counting the number of distinct integral solution of a given equation. This abstraction is extremely useful for solving Combinatorial problems.
What if had 2 different prime factors? Suppose . Since , it is clear that each will have atmost 2 prime factors, i.e, and .
Assume . Then
So we are looking for the number of non-negative solution to
Notice that all are correlated to each other, all are correlated to each other (because their sum is fixed). However, does not interact with . Hence, they are independent. So the total number of ways is equal to the product of the number of ways to find and , which is nothing but
What if ? Note that the prime factors do not interact with each other. Therefore, the number of distinct arrays with product is equal to
Since , you can compute prime factorization in . Notice that each cannot be bigger than . Why?
Therefore, factorials can be precomputed to compute fast.
This is because the prime factorization of co-prime integers have nothing in common, therefore, the product will contain all prime factors in each number. Hence, none of the primes interacts with each other, even in the multiplication.
Functions that obey this property for co-prime inputs are known as Multiplicative Functions.
Prefix Sum of Multiplicative Functions
How do you find out the number of arrays of length with product ?
We are simply looking for
Naively computing it would lead to TLE, as .
However, since this is a multiplicative function, there exists a dynamic programming solution to compute the prefix sum of multiplicative functions efficiently. I might add another blog on this topic in future, but feel free to google the keyword and do your own research.