_long.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. from c import sizeof
  2. # https://www.cnblogs.com/liuchanglc/p/14203783.html
  3. if sizeof('void_p') == 4:
  4. PyLong_SHIFT = 28//2 - 1
  5. PyLong_NTT_P = 12289
  6. PyLong_NTT_PR = 11
  7. elif sizeof('void_p') == 8:
  8. PyLong_SHIFT = 60//2 - 1
  9. PyLong_NTT_P = 1004535809 # PyLong_NTT_P**2 should not overflow
  10. PyLong_NTT_PR = 3
  11. else:
  12. raise NotImplementedError
  13. PyLong_BASE = 2 ** PyLong_SHIFT
  14. PyLong_MASK = PyLong_BASE - 1
  15. PyLong_DECIMAL_SHIFT = 4
  16. PyLong_DECIMAL_BASE = 10 ** PyLong_DECIMAL_SHIFT
  17. assert PyLong_NTT_P > PyLong_BASE
  18. #----------------------------------------------------------------------------#
  19. # #
  20. # Number Theoretic Transform #
  21. # #
  22. #----------------------------------------------------------------------------#
  23. def ibin(n, bits):
  24. assert type(bits) is int and bits >= 0
  25. return bin(n)[2:].rjust(bits, "0")
  26. def _number_theoretic_transform(a: list, p, pr, inverse):
  27. n = len(a)
  28. assert n&(n - 1) == 0
  29. a = [x % p for x in a]
  30. b = n.bit_length() - 1
  31. for i in range(1, n):
  32. j = int(ibin(i, b)[::-1], 2)
  33. if i < j:
  34. a[i], a[j] = a[j], a[i]
  35. rt = pow(pr, (p - 1) // n, p)
  36. if inverse:
  37. rt = pow(rt, p - 2, p)
  38. w = [1]*(n // 2)
  39. for i in range(1, n // 2):
  40. w[i] = w[i - 1]*rt % p
  41. h = 2
  42. while h <= n:
  43. hf, ut = h // 2, n // h
  44. for i in range(0, n, h):
  45. for j in range(hf):
  46. u = a[i + j]
  47. v = a[i + j + hf] * w[ut * j] % p
  48. a[i + j] = (u + v) % p
  49. a[i + j + hf] = (u - v + p) % p
  50. h *= 2
  51. if inverse:
  52. rv = pow(n, p - 2, p)
  53. a = [x*rv % p for x in a]
  54. return a
  55. def ntt(a, p, pr):
  56. return _number_theoretic_transform(a, p, pr, False)
  57. def intt(a, p, pr):
  58. return _number_theoretic_transform(a, p, pr, True)
  59. ##############################################################
  60. def ulong_fromint(x: int):
  61. # return a list of digits and sign
  62. if x == 0: return [0], 1
  63. sign = 1 if x > 0 else -1
  64. if sign < 0: x = -x
  65. res = []
  66. while x:
  67. res.append(x & PyLong_MASK)
  68. x >>= PyLong_SHIFT
  69. return res, sign
  70. def ulong_cmp(a: list, b: list) -> int:
  71. # return 1 if a>b, -1 if a<b, 0 if a==b
  72. if len(a) > len(b): return 1
  73. if len(a) < len(b): return -1
  74. for i in range(len(a)-1, -1, -1):
  75. if a[i] > b[i]: return 1
  76. if a[i] < b[i]: return -1
  77. return 0
  78. def ulong_pad_(a: list, size: int):
  79. # pad leading zeros to have `size` digits
  80. delta = size - len(a)
  81. if delta > 0:
  82. a.extend([0] * delta)
  83. def ulong_unpad_(a: list):
  84. # remove leading zeros
  85. while len(a)>1 and a[-1]==0:
  86. a.pop()
  87. def ulong_add(a: list, b: list) -> list:
  88. res = [0] * max(len(a), len(b))
  89. ulong_pad_(a, len(res))
  90. ulong_pad_(b, len(res))
  91. carry = 0
  92. for i in range(len(res)):
  93. carry += a[i] + b[i]
  94. res[i] = carry & PyLong_MASK
  95. carry >>= PyLong_SHIFT
  96. if carry > 0:
  97. res.append(carry)
  98. return res
  99. def ulong_sub(a: list, b: list) -> list:
  100. # a >= b
  101. res = []
  102. borrow = 0
  103. for i in range(len(b)):
  104. tmp = a[i] - b[i] - borrow
  105. if tmp < 0:
  106. tmp += PyLong_BASE
  107. borrow = 1
  108. else:
  109. borrow = 0
  110. res.append(tmp)
  111. for i in range(len(b), len(a)):
  112. tmp = a[i] - borrow
  113. if tmp < 0:
  114. tmp += PyLong_BASE
  115. borrow = 1
  116. else:
  117. borrow = 0
  118. res.append(tmp)
  119. ulong_unpad_(res)
  120. return res
  121. def ulong_divmodi(a: list, b: int):
  122. # b > 0
  123. res = []
  124. carry = 0
  125. for i in range(len(a)-1, -1, -1):
  126. carry <<= PyLong_SHIFT
  127. carry += a[i]
  128. res.append(carry // b)
  129. carry %= b
  130. res.reverse()
  131. ulong_unpad_(res)
  132. return res, carry
  133. def ulong_floordivi(a: list, b: int):
  134. # b > 0
  135. return ulong_divmodi(a, b)[0]
  136. def ulong_muli(a: list, b: int):
  137. # b >= 0
  138. res = [0] * len(a)
  139. carry = 0
  140. for i in range(len(a)):
  141. carry += a[i] * b
  142. res[i] = carry & PyLong_MASK
  143. carry >>= PyLong_SHIFT
  144. if carry > 0:
  145. res.append(carry)
  146. return res
  147. def ulong_mul(a: list, b: list):
  148. N = len(a) + len(b)
  149. if False:
  150. # use grade-school multiplication
  151. res = [0] * N
  152. for i in range(len(a)):
  153. carry = 0
  154. for j in range(len(b)):
  155. carry += res[i+j] + a[i] * b[j]
  156. res[i+j] = carry & PyLong_MASK
  157. carry >>= PyLong_SHIFT
  158. res[i+len(b)] = carry
  159. ulong_unpad_(res)
  160. return res
  161. else:
  162. # use fast number-theoretic transform
  163. limit = 1
  164. while limit < N:
  165. limit <<= 1
  166. a += [0]*(limit - len(a))
  167. b += [0]*(limit - len(b))
  168. # print(a, b)
  169. a = ntt(a, PyLong_NTT_P, PyLong_NTT_PR)
  170. b = ntt(b, PyLong_NTT_P, PyLong_NTT_PR)
  171. # print(a, b)
  172. c = [0] * limit
  173. for i in range(limit):
  174. c[i] = (a[i] * b[i]) % PyLong_NTT_P
  175. # print(c)
  176. c = intt(c, PyLong_NTT_P, PyLong_NTT_PR)
  177. # print(c)
  178. # handle carry
  179. carry = 0
  180. for i in range(limit-1):
  181. carry += c[i]
  182. c[i] = carry & PyLong_MASK
  183. carry >>= PyLong_SHIFT
  184. if carry > 0:
  185. c[limit-1] = carry
  186. # print(c)
  187. ulong_unpad_(c) # should we use this?
  188. # print(c)
  189. return c
  190. def ulong_powi(a: list, b: int):
  191. # b >= 0
  192. if b == 0: return [1]
  193. res = [1]
  194. while b:
  195. if b & 1:
  196. res = ulong_mul(res, a)
  197. a = ulong_mul(a, a)
  198. b >>= 1
  199. return res
  200. def ulong_repr(x: list) -> str:
  201. res = []
  202. while len(x)>1 or x[0]>0: # non-zero
  203. x, r = ulong_divmodi(x, PyLong_DECIMAL_BASE)
  204. res.append(str(r).zfill(PyLong_DECIMAL_SHIFT))
  205. res.reverse()
  206. s = ''.join(res)
  207. if len(s) == 0: return '0'
  208. if len(s) > 1: s = s.lstrip('0')
  209. return s
  210. def ulong_fromstr(s: str):
  211. if s[-1] == 'L':
  212. s = s[:-1]
  213. res, base = [0], [1]
  214. if s[0] == '-':
  215. sign = -1
  216. s = s[1:]
  217. else:
  218. sign = 1
  219. s = s[::-1]
  220. for c in s:
  221. c = ord(c) - 48
  222. assert 0 <= c <= 9
  223. res = ulong_add(res, ulong_muli(base, c))
  224. base = ulong_muli(base, 10)
  225. return res, sign
  226. class long:
  227. def __init__(self, x):
  228. if type(x) is tuple:
  229. self.digits, self.sign = x
  230. elif type(x) is int:
  231. self.digits, self.sign = ulong_fromint(x)
  232. elif type(x) is float:
  233. self.digits, self.sign = ulong_fromint(int(x))
  234. elif type(x) is str:
  235. self.digits, self.sign = ulong_fromstr(x)
  236. elif type(x) is long:
  237. self.digits, self.sign = x.digits.copy(), x.sign
  238. else:
  239. raise TypeError('expected int or str')
  240. def __add__(self, other):
  241. if type(other) is int:
  242. other = long(other)
  243. elif type(other) is not long:
  244. return NotImplemented
  245. if self.sign == other.sign:
  246. return long((ulong_add(self.digits, other.digits), self.sign))
  247. else:
  248. cmp = ulong_cmp(self.digits, other.digits)
  249. if cmp == 0:
  250. return long(0)
  251. if cmp > 0:
  252. return long((ulong_sub(self.digits, other.digits), self.sign))
  253. else:
  254. return long((ulong_sub(other.digits, self.digits), other.sign))
  255. def __radd__(self, other):
  256. return self.__add__(other)
  257. def __sub__(self, other):
  258. if type(other) is int:
  259. other = long(other)
  260. elif type(other) is not long:
  261. return NotImplemented
  262. if self.sign != other.sign:
  263. return long((ulong_add(self.digits, other.digits), self.sign))
  264. cmp = ulong_cmp(self.digits, other.digits)
  265. if cmp == 0:
  266. return long(0)
  267. if cmp > 0:
  268. return long((ulong_sub(self.digits, other.digits), self.sign))
  269. else:
  270. return long((ulong_sub(other.digits, self.digits), -other.sign))
  271. def __rsub__(self, other):
  272. if type(other) is int:
  273. other = long(other)
  274. elif type(other) is not long:
  275. return NotImplemented
  276. return other.__sub__(self)
  277. def __mul__(self, other):
  278. if type(other) is int:
  279. return long((
  280. ulong_muli(self.digits, abs(other)),
  281. self.sign * (1 if other >= 0 else -1)
  282. ))
  283. elif type(other) is long:
  284. return long((
  285. ulong_mul(self.digits, other.digits),
  286. self.sign * other.sign
  287. ))
  288. return NotImplemented
  289. def __rmul__(self, other):
  290. return self.__mul__(other)
  291. #######################################################
  292. def __divmod__(self, other):
  293. if type(other) is int:
  294. assert type(other) is int and other > 0
  295. assert self.sign == 1
  296. q, r = ulong_divmodi(self.digits, other)
  297. return long((q, 1)), r
  298. raise NotImplementedError
  299. def __floordiv__(self, other: int):
  300. return self.__divmod__(other)[0]
  301. def __mod__(self, other: int):
  302. return self.__divmod__(other)[1]
  303. def __pow__(self, other: int):
  304. assert type(other) is int and other >= 0
  305. if self.sign == -1 and other & 1:
  306. sign = -1
  307. else:
  308. sign = 1
  309. return long((ulong_powi(self.digits, other), sign))
  310. def __lshift__(self, other: int):
  311. assert type(other) is int and other >= 0
  312. x = self.digits.copy()
  313. q, r = divmod(other, PyLong_SHIFT)
  314. x = [0]*q + x
  315. for _ in range(r): x = ulong_muli(x, 2)
  316. return long((x, self.sign))
  317. def __rshift__(self, other: int):
  318. assert type(other) is int and other >= 0
  319. x = self.digits.copy()
  320. q, r = divmod(other, PyLong_SHIFT)
  321. x = x[q:]
  322. if not x: return long(0)
  323. for _ in range(r): x = ulong_floordivi(x, 2)
  324. return long((x, self.sign))
  325. def __neg__(self):
  326. return long((self.digits, -self.sign))
  327. def __cmp__(self, other):
  328. if type(other) is int:
  329. other = long(other)
  330. else:
  331. assert type(other) is long
  332. if self.sign > other.sign:
  333. return 1
  334. elif self.sign < other.sign:
  335. return -1
  336. else:
  337. return ulong_cmp(self.digits, other.digits)
  338. def __eq__(self, other):
  339. return self.__cmp__(other) == 0
  340. def __lt__(self, other):
  341. return self.__cmp__(other) < 0
  342. def __le__(self, other):
  343. return self.__cmp__(other) <= 0
  344. def __gt__(self, other):
  345. return self.__cmp__(other) > 0
  346. def __ge__(self, other):
  347. return self.__cmp__(other) >= 0
  348. def __repr__(self):
  349. prefix = '-' if self.sign < 0 else ''
  350. return prefix + ulong_repr(self.digits) + 'L'