_long.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. elif sizeof('void_p') == 8:
  6. PyLong_SHIFT = 60//2 - 1
  7. else:
  8. raise NotImplementedError
  9. PyLong_BASE = 2 ** PyLong_SHIFT
  10. PyLong_MASK = PyLong_BASE - 1
  11. PyLong_DECIMAL_SHIFT = 4
  12. PyLong_DECIMAL_BASE = 10 ** PyLong_DECIMAL_SHIFT
  13. ##############################################################
  14. def ulong_fromint(x: int):
  15. # return a list of digits and sign
  16. if x == 0: return [0], 1
  17. sign = 1 if x > 0 else -1
  18. if sign < 0: x = -x
  19. res = []
  20. while x:
  21. res.append(x & PyLong_MASK)
  22. x >>= PyLong_SHIFT
  23. return res, sign
  24. def ulong_cmp(a: list, b: list) -> int:
  25. # return 1 if a>b, -1 if a<b, 0 if a==b
  26. if len(a) > len(b): return 1
  27. if len(a) < len(b): return -1
  28. for i in range(len(a)-1, -1, -1):
  29. if a[i] > b[i]: return 1
  30. if a[i] < b[i]: return -1
  31. return 0
  32. def ulong_pad_(a: list, size: int):
  33. # pad leading zeros to have `size` digits
  34. delta = size - len(a)
  35. if delta > 0:
  36. a.extend([0] * delta)
  37. def ulong_unpad_(a: list):
  38. # remove leading zeros
  39. while len(a)>1 and a[-1]==0:
  40. a.pop()
  41. def ulong_add(a: list, b: list) -> list:
  42. res = [0] * max(len(a), len(b))
  43. ulong_pad_(a, len(res))
  44. ulong_pad_(b, len(res))
  45. carry = 0
  46. for i in range(len(res)):
  47. carry += a[i] + b[i]
  48. res[i] = carry & PyLong_MASK
  49. carry >>= PyLong_SHIFT
  50. if carry > 0:
  51. res.append(carry)
  52. return res
  53. def ulong_inc_(a: list):
  54. a[0] += 1
  55. for i in range(len(a)):
  56. if a[i] < PyLong_BASE: break
  57. a[i] -= PyLong_BASE
  58. if i+1 == len(a):
  59. a.append(1)
  60. else:
  61. a[i+1] += 1
  62. def ulong_sub(a: list, b: list) -> list:
  63. # a >= b
  64. res = []
  65. borrow = 0
  66. for i in range(len(b)):
  67. tmp = a[i] - b[i] - borrow
  68. if tmp < 0:
  69. tmp += PyLong_BASE
  70. borrow = 1
  71. else:
  72. borrow = 0
  73. res.append(tmp)
  74. for i in range(len(b), len(a)):
  75. tmp = a[i] - borrow
  76. if tmp < 0:
  77. tmp += PyLong_BASE
  78. borrow = 1
  79. else:
  80. borrow = 0
  81. res.append(tmp)
  82. ulong_unpad_(res)
  83. return res
  84. def ulong_divmodi(a: list, b: int):
  85. # b > 0
  86. res = []
  87. carry = 0
  88. for i in range(len(a)-1, -1, -1):
  89. carry <<= PyLong_SHIFT
  90. carry += a[i]
  91. res.append(carry // b)
  92. carry %= b
  93. res.reverse()
  94. ulong_unpad_(res)
  95. return res, carry
  96. def ulong_divmod(a: list, b: list):
  97. q = [0]
  98. while ulong_cmp(a, b) >= 0:
  99. ulong_inc_(q)
  100. a = ulong_sub(a, b)
  101. return q, a
  102. def ulong_floordivi(a: list, b: int):
  103. # b > 0
  104. return ulong_divmodi(a, b)[0]
  105. def ulong_muli(a: list, b: int):
  106. # b >= 0
  107. res = [0] * len(a)
  108. carry = 0
  109. for i in range(len(a)):
  110. carry += a[i] * b
  111. res[i] = carry & PyLong_MASK
  112. carry >>= PyLong_SHIFT
  113. if carry > 0:
  114. res.append(carry)
  115. return res
  116. def ulong_mul(a: list, b: list):
  117. N = len(a) + len(b)
  118. # use grade-school multiplication
  119. res = [0] * N
  120. for i in range(len(a)):
  121. carry = 0
  122. for j in range(len(b)):
  123. carry += res[i+j] + a[i] * b[j]
  124. res[i+j] = carry & PyLong_MASK
  125. carry >>= PyLong_SHIFT
  126. res[i+len(b)] = carry
  127. ulong_unpad_(res)
  128. return res
  129. def ulong_powi(a: list, b: int):
  130. # b >= 0
  131. if b == 0: return [1]
  132. res = [1]
  133. while b:
  134. if b & 1:
  135. res = ulong_mul(res, a)
  136. a = ulong_mul(a, a)
  137. b >>= 1
  138. return res
  139. def ulong_repr(x: list) -> str:
  140. res = []
  141. while len(x)>1 or x[0]>0: # non-zero
  142. x, r = ulong_divmodi(x, PyLong_DECIMAL_BASE)
  143. res.append(str(r).zfill(PyLong_DECIMAL_SHIFT))
  144. res.reverse()
  145. s = ''.join(res)
  146. if len(s) == 0: return '0'
  147. if len(s) > 1: s = s.lstrip('0')
  148. return s
  149. def ulong_fromstr(s: str):
  150. if s[-1] == 'L':
  151. s = s[:-1]
  152. res, base = [0], [1]
  153. if s[0] == '-':
  154. sign = -1
  155. s = s[1:]
  156. else:
  157. sign = 1
  158. s = s[::-1]
  159. for c in s:
  160. c = ord(c) - 48
  161. assert 0 <= c <= 9
  162. res = ulong_add(res, ulong_muli(base, c))
  163. base = ulong_muli(base, 10)
  164. return res, sign
  165. class long:
  166. def __init__(self, x):
  167. if type(x) is tuple:
  168. self.digits, self.sign = x
  169. elif type(x) is int:
  170. self.digits, self.sign = ulong_fromint(x)
  171. elif type(x) is float:
  172. self.digits, self.sign = ulong_fromint(int(x))
  173. elif type(x) is str:
  174. self.digits, self.sign = ulong_fromstr(x)
  175. elif type(x) is long:
  176. self.digits, self.sign = x.digits.copy(), x.sign
  177. else:
  178. raise TypeError('expected int or str')
  179. def __len__(self):
  180. return len(self.digits)
  181. def __add__(self, other):
  182. if type(other) is int:
  183. other = long(other)
  184. elif type(other) is not long:
  185. return NotImplemented
  186. if self.sign == other.sign:
  187. return long((ulong_add(self.digits, other.digits), self.sign))
  188. else:
  189. cmp = ulong_cmp(self.digits, other.digits)
  190. if cmp == 0:
  191. return long(0)
  192. if cmp > 0:
  193. return long((ulong_sub(self.digits, other.digits), self.sign))
  194. else:
  195. return long((ulong_sub(other.digits, self.digits), other.sign))
  196. def __radd__(self, other):
  197. return self.__add__(other)
  198. def __sub__(self, other):
  199. if type(other) is int:
  200. other = long(other)
  201. elif type(other) is not long:
  202. return NotImplemented
  203. if self.sign != other.sign:
  204. return long((ulong_add(self.digits, other.digits), self.sign))
  205. cmp = ulong_cmp(self.digits, other.digits)
  206. if cmp == 0:
  207. return long(0)
  208. if cmp > 0:
  209. return long((ulong_sub(self.digits, other.digits), self.sign))
  210. else:
  211. return long((ulong_sub(other.digits, self.digits), -other.sign))
  212. def __rsub__(self, other):
  213. if type(other) is int:
  214. other = long(other)
  215. elif type(other) is not long:
  216. return NotImplemented
  217. return other.__sub__(self)
  218. def __mul__(self, other):
  219. if type(other) is int:
  220. return long((
  221. ulong_muli(self.digits, abs(other)),
  222. self.sign * (1 if other >= 0 else -1)
  223. ))
  224. elif type(other) is long:
  225. return long((
  226. ulong_mul(self.digits, other.digits),
  227. self.sign * other.sign
  228. ))
  229. return NotImplemented
  230. def __rmul__(self, other):
  231. return self.__mul__(other)
  232. #######################################################
  233. def __divmod__(self, other):
  234. if type(other) is int:
  235. assert self.sign == 1 and other > 0
  236. q, r = ulong_divmodi(self.digits, other)
  237. return long((q, 1)), r
  238. if type(other) is long:
  239. assert self.sign == 1 and other.sign == 1
  240. q, r = ulong_divmod(self.digits, other.digits)
  241. assert len(other)>1 or other.digits[0]>0
  242. return long((q, 1)), long((r, 1))
  243. raise NotImplementedError
  244. def __floordiv__(self, other):
  245. return self.__divmod__(other)[0]
  246. def __mod__(self, other):
  247. return self.__divmod__(other)[1]
  248. def __pow__(self, other: int):
  249. assert type(other) is int and other >= 0
  250. if self.sign == -1 and other & 1:
  251. sign = -1
  252. else:
  253. sign = 1
  254. return long((ulong_powi(self.digits, other), sign))
  255. def __lshift__(self, other: int):
  256. assert type(other) is int and other >= 0
  257. x = self.digits.copy()
  258. q, r = divmod(other, PyLong_SHIFT)
  259. x = [0]*q + x
  260. for _ in range(r): x = ulong_muli(x, 2)
  261. return long((x, self.sign))
  262. def __rshift__(self, other: int):
  263. assert type(other) is int and other >= 0
  264. x = self.digits.copy()
  265. q, r = divmod(other, PyLong_SHIFT)
  266. x = x[q:]
  267. if not x: return long(0)
  268. for _ in range(r): x = ulong_floordivi(x, 2)
  269. return long((x, self.sign))
  270. def __neg__(self):
  271. return long((self.digits, -self.sign))
  272. def __cmp__(self, other):
  273. if type(other) is int:
  274. other = long(other)
  275. elif type(other) is not long:
  276. return NotImplemented
  277. if self.sign > other.sign:
  278. return 1
  279. elif self.sign < other.sign:
  280. return -1
  281. else:
  282. return ulong_cmp(self.digits, other.digits)
  283. def __eq__(self, other):
  284. return self.__cmp__(other) == 0
  285. def __lt__(self, other):
  286. return self.__cmp__(other) < 0
  287. def __le__(self, other):
  288. return self.__cmp__(other) <= 0
  289. def __gt__(self, other):
  290. return self.__cmp__(other) > 0
  291. def __ge__(self, other):
  292. return self.__cmp__(other) >= 0
  293. def __repr__(self):
  294. prefix = '-' if self.sign < 0 else ''
  295. return prefix + ulong_repr(self.digits) + 'L'