Advertisement
newb_ie

mod

Mar 15th, 2021
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | None | 0 0
  1. class Combination:
  2.     def __init__(self, n_max=0, mod=-1):
  3.         self.init(n_max, mod)
  4.     def init(self, n_max, mod=1000000007):
  5.         self.mod = mod
  6.         if mod != -1:
  7.             self.modinv = self.make_modinv_list(n_max)
  8.             self.fac, self.facinv = self.make_factorial_list(n_max)
  9.     def __call__(self, n, r):
  10.         if self.mod == -1:
  11.             return self.cmb(n, r)
  12.         else:
  13.             return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n - r] % self.mod
  14.     def make_factorial_list(self, n):
  15.         fac = [1]
  16.         facinv = [1]
  17.         for i in range(1, n + 1):
  18.             fac.append(fac[i - 1] * i % self.mod)
  19.             facinv.append(facinv[i - 1] * self.modinv[i] % self.mod)
  20.         return fac, facinv
  21.  
  22.     def make_modinv_list(self, n):
  23.         modinv = [0] * (n + 1)
  24.         modinv[1] = 1
  25.         for i in range(2, n + 1):
  26.             modinv[i] = self.mod - self.mod // i * modinv[self.mod % i] % self.mod
  27.         return modinv
  28.  
  29.     def cmb(self, n, r):
  30.         if n - r < r:
  31.             r = n - r
  32.         if r == 0:
  33.             return 1
  34.         if r == 1:
  35.             return n
  36.         numerator = [n - r + k + 1 for k in range(r)]
  37.         denominator = [k + 1 for k in range(r)]
  38.         for p in range(2, r + 1):
  39.             pivot = denominator[p - 1]
  40.             if pivot > 1:
  41.                 offset = (n - r) % p
  42.                 for k in range(p - 1, r, p):
  43.                     numerator[k - offset] /= pivot
  44.                     denominator[k] /= pivot
  45.         result = 1
  46.         for k in range(r):
  47.             if numerator[k] > 1:
  48.                 result *= int(numerator[k])
  49.         return result
  50.  
  51.  
  52. from sys import stdin
  53. from collections import defaultdict
  54. input = stdin.readline
  55. # ~ T = int(input())
  56. T = 1
  57. for t in range(1,T + 1):
  58.    
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement