I want to find nCr Mod p where n,r is big integer <= 10^6 and P is a prime number, how can i do this ?
№ | Пользователь | Рейтинг |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3885 |
3 | jqdai0815 | 3682 |
4 | Benq | 3580 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3506 |
7 | ecnerwala | 3505 |
8 | Radewoosh | 3457 |
9 | Kevin114514 | 3377 |
10 | gamegame | 3374 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 170 |
2 | Um_nik | 162 |
3 | atcoder_official | 161 |
4 | maomao90 | 158 |
4 | -is-this-fft- | 158 |
6 | djm03178 | 157 |
7 | Dominater069 | 156 |
8 | adamant | 154 |
9 | luogu_official | 153 |
10 | awoo | 152 |
I want to find nCr Mod p where n,r is big integer <= 10^6 and P is a prime number, how can i do this ?
Название |
---|
nCr(mod p) = n!(mod p) * inv(r!(mod p)) * inv((n-r)! Mod p) % p where n! (mod p) can be calculated in linear time and inverse n! modulo p can be calculated in O(nlogp) time for all n(preprocessing).
You can calculate inverse n! mod p in linear time in kind of a hacky way.
Let's say you want to calculate $$$n!^{-1}$$$ up to MAXN. First, calculate $$$MAXN!^{-1}$$$ offline. Now, loop down from MAXN down to 1, doing $$$n!^{-1}*n = (n-1)!^{-1}$$$.
For a less hacky way, you can calculate all the modular inverses up to n with:
Then simply use another loop to calculate prefix products of this. See this blog for why it works.
Of course, it's going to have a worse constant than the hacky way because of all the % operations, but I haven't tested exactly how much worse it is. I'm guessing not enough to matter for the average problem, and it's certainly better than the O(nlogp) way.
How $$$n!^{-1}$$$ * $$$n$$$ = $$$(n-1)!^{-1}$$$
$$$n!^{-1} * n \equiv n^{-1} * (n - 1)^{-1} * n \equiv n * n^{-1} * (n - 1)^{-1} \equiv (n - 1)^{-1} \pmod{m}$$$
try using Lucas's Algorithm. Hope it helps!
nCr % p using Fermat Little Theorem Hope this helps you .