Your approach to solve SANDWICH?

I didn’t use lucas theorem. I just solved it using CRT and by finding Modular multiplicative inverses.

Let n=⌈NK

and x = (K × n) - N

So, as we have to distribute x vacancies in n parts, the number of ways is n+x-1Cx

Let the prime factorization of M = p1e1×p2e2×p3e3×p4e4 …×ptet

Here t is the total no of unique prime factors.

Here piei and pjej are coprime for any 1 ≤ (i≠j) ≤ t

So if we find n+x-1Cx Mod piei for each i,
We can then combine the results to find n+x-1Cx Mod M using CRT

Note that if x! and (n-1)! don’t have any factors of pi then they would have unique

modular multiplicative inverse.

The main issue that we face now is that (n-1)! and x! could have factors of pi

Let y be the highest power of pi which divides x!

Then let F(x,piei) = ((x!)/piy) Mod piei
As F(x,piei) is not divisible by pi, we can find its modular multiplicative inverse.

We can later on deal with the total power of pi in n+x-1Cx and multiply it to our answer.

So n+x-1Cx Mod piei will be (piz × F(x+n-1,piei))/(F(x,piei) × F(n-1,piei)) Mod piei

Here z is the highest power of pi which divides n+x-1Cx

To find F(x,piei), the trick here is to take all the numbers divisible by pi out of the factorial.

Notice that we take out precisely (⌊xpi⌋!)×pi⌊x⁄pi⌋ out of the factorial.

Now let H = x!/((⌊xpi⌋!)×pi⌊x⁄pi⌋) Mod piei
(Note: H is basically x! with all terms divisible by pi ignored)

H can be found in in O(piei+ log x) using fast exponentiation as

all numbers in the factorial repeat after piei numbers Mod piei

Now we can say that F(x,piei)=H×F(⌊xpi⌋,piei)

This is a recurrence relation, so the over all complexity is O((piei+log x)×(log x))

We now know how to find F(x,piei)

Now we need to know how to find the power of pi in x!.

This is simply Σ ⌊xpic where c is a natural number.

Here is my solution - CodeChef: Practical coding for everyone

PS:- The recursive part can be optimized by making it iterative.

That reduces the overall complexity to O(M + (log2(N+k)×(log M)))

15 Likes