This problem can be solved using Legendre’s Formula and Prime Factorization.


Legendre's Formula: Let mm be a prime number, and we call it p,p, then the exponent of pp in the prime factorization of n!n! is:

f(n,p)=np+np2+np3+f(n, p) = ⌊\frac{n}{p}⌋ + ⌊\frac{n}{p^2}⌋ + ⌊\frac{n}{p^3}⌋ +… until pxp^x is less than or equal to n.n.


When mm is not a prime, then we need to express the composite number mm as a product of its prime factors (Prime factorization). Let's say, mm = p1c1p2c2p3c3pkckp_1^{c_1}\cdot p_2^{c_2}\cdot p_3^{c_3}\cdot …\cdot p_k^{c_k} where p1,p2,p3,,pkp_1, p_2, p_3,…, p_k are distinct prime factors of mm and c1,c2,c3,,ckc_1, c_2, c_3,…, c_k are the corresponding exponents.


For each prime factor pip_i (where 1ik1≤i≤k) we can use Legendre's formula to find the exponent of pip_i in the prime factorization of n!.n!. Then the largest exponent of mm that divide n!n! would be the minimum of ƒ(n,pi)ƒ(n, p_i) divided by ci.c_i.

mini=1kf(n, pi)cimin_{i = 1}^k⌊\frac{f (n,\space p_i)}{c_i}⌋


Now, what is the largest exponent of mm that divides nCr?^nC_r?

For each prime factor pip_i (where 1ik1≤i≤k) we can apply Legendre's formula to find the exponent of pip_i in the prime factorization of n!,r!n!, r! and (nr)!(n - r)! separately. Then subtract the exponents we get for r!r! and (nr)!(n - r)! from the exponent for n!n! to find the exponent of pip_i in the prime factorization of nCr.^nC_r.

So, the largest exponent of mm that divides nCr^nC_r would be:

mini=1kf(n, pi)f(r, pi)f(nr, pi)cimin_{i = 1}^k⌊\frac{f(n,\space p_i) - f(r,\space p_i) - f(n - r,\space p_i)}{c_i}⌋


Time and Space complexity: To avoid worst-case time complexity, use Sieve of Eratosthenes algorithm to store all primes up to 106,10^6, facilitating efficient prime factorization of m.m.


Let, N=106,N = 10^6, then to store all prime up to NN using Sieve of Eratosthenes:

Time complexity, O(Nlog(log(N)))O(N\cdot log(log(N)))

Space complexity, O(N)O(N)


Let, SS be the number of primes which are less than or equal to m.\sqrt m. Then in each test cases, prime factorization of mm using stored primes:

Time complexity, O(TS)O(T\cdot S)

In the worst case, SS can be at most 7849878\, 498 (Number of primes less than or equal to 10610^6). However, it’s still enough to pass within the given time limit.


So, the overall complexity of our solution:

Time complexity, O(Nlog(log(N))+TS)O(N\cdot log(log(N)) + T\cdot S)

Space complexity, O(N)O(N)

All other complexities are small enough to be neglected.

Statistics

0% Solution Ratio
Toph uses cookies. By continuing you agree to our Cookie Policy.