Please share how you approached solving SANDWICH, even if you didn’t get AC. It will help us to understand how to tackle more mathematically oriented problems.

Thank you

I used dp to solve it, only test case 1 passed, idea was kind of similar to rod cutting problem Link

Basically you needed to use generalized lucas’s theorem. First covert the solution to aCb form where

a = ans1-1

b = a+(ans1*k-n)

Now, I could solve it for 50 pnts as I couldn’t understand generalized lucas’s theorem but here are some links to calculate nCr % m

https://discuss.codechef.com/questions/3869/best-known-algos-for-calculating-ncr-m

www.dms.umontreal.ca/~andrew/Binomial/genlucas.html

You can google for more.

After some observation, I found that the answer would be (N/K +R)cR where N is the length of the sandwhich and R=K-(N%k). Wasn’t able to solve it for when M was not prime tho as inverse could not be found.

Here’s my code (it’s a bit messy tho):

https://www.codechef.com/viewsolution/13530263

P.S: I just noticed we have the exact same rating(before the updation of this contests ratings.). What a coincidence xD.

First I came up with a dynamic programming approach in O(N^3), then i test for pattern on small test. After that I realize **f[i] = 1 with i<k or i%k==0, otherwise f[i] = f[i-k] + f[i-k+1] + … + f[[i/k] k-1]* which can be calculated in O(N). Still thinking for subtask 3 and 4…

Answer was easily reduced to N C K mod m , where m is not prime . If m would have been prime , it would be easily solvable by lucas theorem . But here m is not necessarily prime. So, there were various algorithms to do that too. I am not sure since i got 50 only. One idea was to break m into it’s prime factors. Let us say:

m = p1^k1 * p2^k2 * p3^k3…

Now we can find answer to each factor by “generalized lucas theorem” and combine answers by CRT.

source: Best known algos for calculating nCr % M - tutorial - CodeChef Discuss

Another approach is discussed here :

http://m00nlight.github.io/algorithm/2015/04/11/hackerrank-ncr

First thing which you have to see that

Answer is ^{n+n*K-N-1}C_{n-1} where n=\lceil \frac{N}{K} \rceil

Now for N as large as 10^{18} and M non-prime, you will have to use the generalization of Lucas theorem for prime powers.

And after calculating answer modulo all the prime powers present in M, you will have to use Chinese remainder theorem.

Lucas theorem for prime powers is Theorem 1(page 2) in this research paper.

{\frac{n}{k} - {n \% k} + k} \choose {\frac{n}{k}} is the solution for the sandwich problem.

Honestly this came as an observation rather than some Mathematics.

Once this is identified, the problem becomes more of the optimization problem.

Things you need for solving this.

- Prime Factorization (Sieving and storing smallest prime factor will get this done in O(log N)
- General Lucas Theorem, Calculate {{\frac{n}{k} - {n \% k} + k} \choose {\frac{n}{k}}} \% p^k where P is prime and k is the highest of power of P in M. Calculate this for all prime factors P.
- Combine them using the Chinese Remainder Theorem

Refer https://arxiv.org/pdf/1301.0252.pdf for General Lucas Theorem.

Here is a implementation of CRT → Implementation of Chinese Remainder theorem (Inverse Modulo based implementation) - GeeksforGeeks

Vote this answer, if you feel like. Karma needed for asking questions

Sandwich is pure math. You can easily determine number of pieces you must cut your sandwich, let’s call it T. Now imagine that you cut a sandwich of length l=k*T. That sandwich can be cut only one way and l>=n. Now to produce all ways to cut our original sandwich we must distribute (l-n) “shortenings by one” between T pieces. That is “Stars and bars” problem

Stars and bars (combinatorics) - Wikipedia.

Now you only need to know how to calculate C(n0, k0) modulo M for very large n0 and k0 (not n and k from a problem, but easily derived from them). For that we need to factorise M. Now suppose that M have some prime divisor p1 and M is divisible by pow(p1, k1), but not divisible by pow(p1, k1+1). Let n0!=pow(p1, t1)*q1, where q1 and p1 are coprime. We need to calculate t1 and q1 modulo pow(p1, k1) for each prime divisor of M. (e-maxx has similar algorithm, although not exactly one needed). After that we can use Chinese Remainder Theorem and reprsent n!=pow(p1, t1)*pow(p2, t2)…*pow(pi, ti)*Qn, where Qn and M are coprime (we don’t need Qn itself, only Qn modulo M).

We must do previous part for all three factorials and then divide one by two others (subtract powers for prime divisors and divide in ring for Qn’s)

For 50 pts : Python users could use this inbuilt function **scipy.misc.comb(N, R, exact=True) **as mentioned in my solution : Python

However for 100 pts the topic involved were 1. Lucas Theorem 2. Chinese Remainder Theorem 3. Wilson Theorem which gave an AC and can be referred by link mentioned in my Java code : here

PS !! Test cases were again weak !!

Passed subtask c ( M is prime ) in O(k) using normal nCr dp and biginteger in java !!

Two more links:

Combinatorics - Mathematics Stack Exchange:

nCr - HackerRank:

http://m00nlight.github.io/algorithm/2015/04/11/hackerrank-ncr

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

Let n=⌈^{N}⁄_{K}⌉

and x = (K × n) - N

So, as we have to distribute **x** vacancies in **n** parts, the number of ways is ^{n+x-1}C_{x}

Let the prime factorization of **M** = p_{1}^{e1}×p_{2}^{e2}×p_{3}^{e3}×p_{4}^{e4} …×p_{t}^{et}

Here **t** is the total no of unique prime factors.

Here p_{i}^{ei} and p_{j}^{ej} are coprime for any 1 ≤ (i≠j) ≤ t

So if we find ** ^{n+x-1}C_{x}** Mod

**p**for each

_{i}^{ei}**i**,

We can then combine the results to find

**Mod**

^{n+x-1}C_{x}**M**using

**CRT**

Note that if x! and (n-1)! don’t have any factors of p_{i} 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 p_{i}

Let y be the highest power of p_{i} which divides x!

Then let **F(x,p _{i}^{ei}) = ((x!)/p_{i}^{y}) Mod p_{i}^{ei}**As F(x,p

_{i}

^{ei}) is not divisible by p

_{i}, we can find its modular multiplicative inverse.

We can later on deal with the total power of p_{i} in ** ^{n+x-1}C_{x}** and multiply it to our answer.

So ^{n+x-1}C_{x} Mod p_{i}^{ei} will be **(p _{i}^{z} × F(x+n-1,p_{i}^{ei}))/(F(x,p_{i}^{ei}) × F(n-1,p_{i}^{ei})) Mod p_{i}^{ei}**

Here **z** is the highest power of **p _{i}** which divides

^{n+x-1}C_{x}To find **F(x,p _{i}^{ei})**, the trick here is to take all the numbers divisible by

**p**out of the factorial.

_{i}Notice that we take out precisely **(⌊ ^{x}⁄_{pi}⌋!)×p_{i}^{⌊x⁄pi⌋}** out of the factorial.

Now let **H = x!/((⌊ ^{x}⁄_{pi}⌋!)×p_{i}^{⌊x⁄pi⌋}) Mod p_{i}^{ei}**

(Note:

**H**is basically

**x!**with all terms divisible by

**p**ignored)

_{i}**H** can be found in in **O(p _{i}^{ei}+ log x)** using fast exponentiation as

all numbers in the factorial repeat after **p _{i}^{ei}** numbers

**Mod p**

_{i}^{ei}Now we can say that **F(x,p _{i}^{ei})**=

**H**×

**F(⌊**

^{x}⁄_{pi}⌋,p_{i}^{ei})This is a recurrence relation, so the over all complexity is **O((p _{i}^{ei}+log x)×(log x))**

We now know how to find **F(x,p _{i}^{ei})**

Now we need to know how to find the power of **p _{i}** in

**x!**.

This is simply **Σ ⌊ ^{x}⁄_{pic}⌋ ** 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 + (log ^{2}(N+k)×(log M))) **

Nobody seems to have shed some light on how to calculate \binom{a}{b}\ mod\ (p^k). We don’t need any research paper to calculate that just some group theory. First let us get rid of all the prime powers of p in \binom{n}{r}. Now let us consider a finite group where X = \{ x : x < p^k, gcd(x, p^k) = 1 \}. Now we can see that this is abelian group [commutative group] under multiplication. So, we can see that if we multiply all the elements of this group and take mod\ (p^k)\ i.e\ x_1.x_2.x_3...x_i.. = -1\ if\ p^k = 4\ or\ p^k\ is\ power\ of\ odd\ prime\ and\ +1\ otherwise. Now to calculate n!\ mod\ p^k[remember we’ve got rid of all the prime powers earlier], we see n!\ \equiv (\pm 1)^{\dfrac{n}{p^k}}.(1.2.3..(n\ mod\ p^k)). (n / p)!\ (mod\ p^k). This is a simple recursive equation which we can calculate in O(p^k\ log\ n) time. Similarly calculate (n - r)!\ \&\ (r!). Take their inverses using extended euclidean and apply chinese remainder theorem.

For

Subtask 1:

Brute force nCr calculations would work. No overflow worry. Easy 10 points.

```
Subtask 2 and 3:
For prime M, Lucas theorem([Lucas Theorem][1])
and for non prime M, DP based method to calculate nCr will work([DP-nCr][2])
```

Subtask 4:

Requires complete implementation of Chinese Remainder Theorem.

@shashank96,(https://discuss.codechef.com/questions/98129/your-approach-to-solve-sandwich?page=1#98152)

I derived that formula so I can shed some light on the approach.

Lets take n=13,k=4.

then one such way to distribute this is:

4|4|4|1

Now, we can move some of the value from the first 3 slots to the last slot ‘1’.

we can add a max value of 3 to the last slot since 1+3=k and we cannot have a piece with >k length.

So, by using multinomial theorem,we need to find solutions to:

x1+x2+x3<=3

which is the same as x1+x2+x3+x4=3.

Also the limits for xi can be take to be infinity since their upper bound is greater than the value on RHS.

We know that the formula for non-negative solutions of x1+x2+x3…+xm=p is:

(p+m-1)C(m-1)

Its easy to see that m=(ceil(n/k)) and p=(k-n%k).

Only two special cases:

- When n%k=0, then there is only 1 way to cut and number of pieces =n/k.
- when k>=n, number of pieces=1,number of ways=1.

I did it using inclusion exclusion principle here ie we distribute balls( = n-k) into boxes ( ceil(n/k) ) with maximum of k balls in each box and to calculate this I used 1. Lucas Theorem 2. Chinese Remainder Theorem. The approach for this is explained here (Q.2 - Life is Strange 4th subtask).

But sadly I could pass only 3 subtasks, I couldn’t figure out the shorter version of formula.

Link for my solution.

I have used Generalized Lucas theorem and CRT to solve the problem using the same paper mentioned by some users who have already answered in this thread. I don’t know why I get WA on only 1 test case. Throughout the contest I have had 30 submissions for this problem with different changes in code to avoid overflows and all but I still could not get it. Please, can someone tell me what is wrong with my code? Thank you in advance to anyone who tries to look through my code.

Solution: CodeChef: Practical coding for everyone

@ista2000 WA was because of overflow only!!

See this:

https://www.codechef.com/viewsolution/13632506

There was overflow happening where you calculate the value of ret in f function.

I just placed %x more cautiously.

Here you can find a decent explanation and code in c++ and python for the nCr (large n and r) problem which includes handling the case of prime powers :). I also found the paper by Andrew Granville which seems to explain the same but it was too complex for me to understand.

I used the code found in this link but gave the guy full credit in the code :). I learned something in this contest which is cool :).

Hope it helps.

http://m00nlight.github.io/algorithm/2015/04/11/hackerrank-ncr