Блог пользователя dreamoon_love_AA

Автор dreamoon_love_AA, 14 лет назад, По-английски

Firstly, we denote the multiplicative inverse of x mod p as inv(x,p).

  1. use dp method to calculation x! mod p for x=1 ~ n (1<=n<p, p is some prime)
  2. calculate inv(n!,p) utilize Extended Euclidean algorithm.
  3. use dp again to calculate inv(x!,p) for x=n-1 ~ 1 with the fact inv(x!,p) * x = inv((x-1)!, p)
  4. now, if we want to now inv(x,p) for some x in [1,n], we only need to calculate (x-1)! * inv(x!,p)
  • Проголосовать: нравится
  • +38
  • Проголосовать: не нравится

»
14 лет назад, скрыть # |
 
Проголосовать: нравится +12 Проголосовать: не нравится

Or just do the following:

inv[1] = 1;
for (int i=2; i<p; ++i)
	inv[i] = (p - (p/i) * inv[p%i] % p) % p;
»
14 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

2. calculate inv(x!,p)
Do you mean inv(n!,p)?
we only need to calculate (x-1)! * inv(x,p)
Do you mean (x-1)! * inv(x!,p)?

»
14 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Nice method! The also exists O(NloglogN) dp solution, which is slower, but seems to be very easy to implement. Let f[x] be the smallest prime, which divides x. We can calculate f[x] for all x in range 1...n using sieve of Eratosthenes. Then we can calculate inv[x] using formula inv[x]=(inv[x/f[x]]*inv[f[x]])%mod.

»
13 лет назад, скрыть # |
 
Проголосовать: нравится +8 Проголосовать: не нравится

Is the following function correct to calculate nCr? ( n Choose r )

i64 nCr(i64 n,i64 r)
{
    i64 c=(inv[r]*inv[n-r])%modL;
    return (fac[n]*c)%modL;
}

(inv[x] is Modular Multiplicative Inverse of x!(x factorial) and fac[x] is x!. i64 is macro of long long. modL is large prime number.)

»
5 лет назад, скрыть # |
Rev. 2  
Проголосовать: нравится -19 Проголосовать: не нравится

sorry, i wrote this under wrong blog announcement