I am stuck on this following problem:
Statement:
Given n, r, x and P where P is a PRIME number.
Print the value nCr % P^x
Constraints:
1 <= r <= n <= 1e12
2 <= x <= 20
2 <= P^x <= 1e6
Thanks for reading the problem. It will be really helpful if you can give me a solution.








When we try to find out (a * b) % m, then ((a % m) * (b % m)) % m will also give the same answer. Because it follows the commutative property. But during (a / b) % m if we do ((a % m) / (b % m)) % m, it will give us the wrong answer. Because it does not follow the commutative property.
In your case nCr = n! / (r! * (n — r)!). So to find this answer with mod. You need to use modular inverse. Learn modular inverse first. Then you will understand everything.
Yes I can do modulo inverse in r! and (n-r)!
But the problem arise when I have to calculate the factorial as its constraints is very big
What if n is 1e12 and r is 5e11... It cant fit the timelimit in trivial way!
Thanks for your time.
Ops! My bad I didn't notice the constraints and your rating. I thought that it was just for the modular inverse. sorry :)
I've got good news and bad news. The good news is that this paper has the answer, and is an interesting read overall. The bad news is that the authors really did not write with programmers in mind.
Thanks for your time
This solution will be helpful Thank you
https://cp-algorithms.com/combinatorics/binomial-coefficients.html#binomial-coefficient-for-large-n-and-small-modulo
This?
yes yes but this method only works if M is prime what if M is not ptime but prime power
Cant find a way :(
It can be solved by exLucas algorithm. To study it, search on the Internet.
ExLucas can solve $$$\binom nm\mod p$$$ of any $$$0\le m\le n$$$ and $$$0 \lt p\le 10^6$$$.
This is my code if you want to have a look.
If anybody found mistake in code, feel free to reply.
Thank you for your time and help
https://www.hackerrank.com/challenges/ncr/problem
Here is a related problem, can see if interested
I got WA.
My code was hacked :(
You can see others' code.