1
0

_long.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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_sub(a: list, b: list) -> list:
  54. # a >= b
  55. res = []
  56. borrow = 0
  57. for i in range(len(b)):
  58. tmp = a[i] - b[i] - borrow
  59. if tmp < 0:
  60. tmp += PyLong_BASE
  61. borrow = 1
  62. else:
  63. borrow = 0
  64. res.append(tmp)
  65. for i in range(len(b), len(a)):
  66. tmp = a[i] - borrow
  67. if tmp < 0:
  68. tmp += PyLong_BASE
  69. borrow = 1
  70. else:
  71. borrow = 0
  72. res.append(tmp)
  73. ulong_unpad_(res)
  74. return res
  75. def ulong_divmodi(a: list, b: int):
  76. # b > 0
  77. res = []
  78. carry = 0
  79. for i in range(len(a)-1, -1, -1):
  80. carry <<= PyLong_SHIFT
  81. carry += a[i]
  82. res.append(carry // b)
  83. carry %= b
  84. res.reverse()
  85. ulong_unpad_(res)
  86. return res, carry
  87. def ulong_floordivi(a: list, b: int):
  88. # b > 0
  89. return ulong_divmodi(a, b)[0]
  90. def ulong_muli(a: list, b: int):
  91. # b >= 0
  92. res = [0] * len(a)
  93. carry = 0
  94. for i in range(len(a)):
  95. carry += a[i] * b
  96. res[i] = carry & PyLong_MASK
  97. carry >>= PyLong_SHIFT
  98. if carry > 0:
  99. res.append(carry)
  100. return res
  101. def ulong_mul(a: list, b: list):
  102. N = len(a) + len(b)
  103. # use grade-school multiplication
  104. res = [0] * N
  105. for i in range(len(a)):
  106. carry = 0
  107. for j in range(len(b)):
  108. carry += res[i+j] + a[i] * b[j]
  109. res[i+j] = carry & PyLong_MASK
  110. carry >>= PyLong_SHIFT
  111. res[i+len(b)] = carry
  112. ulong_unpad_(res)
  113. return res
  114. def ulong_powi(a: list, b: int):
  115. # b >= 0
  116. if b == 0: return [1]
  117. res = [1]
  118. while b:
  119. if b & 1:
  120. res = ulong_mul(res, a)
  121. a = ulong_mul(a, a)
  122. b >>= 1
  123. return res
  124. def ulong_repr(x: list) -> str:
  125. res = []
  126. while len(x)>1 or x[0]>0: # non-zero
  127. x, r = ulong_divmodi(x, PyLong_DECIMAL_BASE)
  128. res.append(str(r).zfill(PyLong_DECIMAL_SHIFT))
  129. res.reverse()
  130. s = ''.join(res)
  131. if len(s) == 0: return '0'
  132. if len(s) > 1: s = s.lstrip('0')
  133. return s
  134. def ulong_fromstr(s: str):
  135. if s[-1] == 'L':
  136. s = s[:-1]
  137. res, base = [0], [1]
  138. if s[0] == '-':
  139. sign = -1
  140. s = s[1:]
  141. else:
  142. sign = 1
  143. s = s[::-1]
  144. for c in s:
  145. c = ord(c) - 48
  146. assert 0 <= c <= 9
  147. res = ulong_add(res, ulong_muli(base, c))
  148. base = ulong_muli(base, 10)
  149. return res, sign
  150. class long:
  151. def __init__(self, x):
  152. if type(x) is tuple:
  153. self.digits, self.sign = x
  154. elif type(x) is int:
  155. self.digits, self.sign = ulong_fromint(x)
  156. elif type(x) is float:
  157. self.digits, self.sign = ulong_fromint(int(x))
  158. elif type(x) is str:
  159. self.digits, self.sign = ulong_fromstr(x)
  160. elif type(x) is long:
  161. self.digits, self.sign = x.digits.copy(), x.sign
  162. else:
  163. raise TypeError('expected int or str')
  164. def __add__(self, other):
  165. if type(other) is int:
  166. other = long(other)
  167. elif type(other) is not long:
  168. return NotImplemented
  169. if self.sign == other.sign:
  170. return long((ulong_add(self.digits, other.digits), self.sign))
  171. else:
  172. cmp = ulong_cmp(self.digits, other.digits)
  173. if cmp == 0:
  174. return long(0)
  175. if cmp > 0:
  176. return long((ulong_sub(self.digits, other.digits), self.sign))
  177. else:
  178. return long((ulong_sub(other.digits, self.digits), other.sign))
  179. def __radd__(self, other):
  180. return self.__add__(other)
  181. def __sub__(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. cmp = ulong_cmp(self.digits, other.digits)
  189. if cmp == 0:
  190. return long(0)
  191. if cmp > 0:
  192. return long((ulong_sub(self.digits, other.digits), self.sign))
  193. else:
  194. return long((ulong_sub(other.digits, self.digits), -other.sign))
  195. def __rsub__(self, other):
  196. if type(other) is int:
  197. other = long(other)
  198. elif type(other) is not long:
  199. return NotImplemented
  200. return other.__sub__(self)
  201. def __mul__(self, other):
  202. if type(other) is int:
  203. return long((
  204. ulong_muli(self.digits, abs(other)),
  205. self.sign * (1 if other >= 0 else -1)
  206. ))
  207. elif type(other) is long:
  208. return long((
  209. ulong_mul(self.digits, other.digits),
  210. self.sign * other.sign
  211. ))
  212. return NotImplemented
  213. def __rmul__(self, other):
  214. return self.__mul__(other)
  215. #######################################################
  216. def __divmod__(self, other):
  217. if type(other) is int:
  218. assert type(other) is int and other > 0
  219. assert self.sign == 1
  220. q, r = ulong_divmodi(self.digits, other)
  221. return long((q, 1)), r
  222. raise NotImplementedError
  223. def __floordiv__(self, other: int):
  224. return self.__divmod__(other)[0]
  225. def __mod__(self, other: int):
  226. return self.__divmod__(other)[1]
  227. def __pow__(self, other: int):
  228. assert type(other) is int and other >= 0
  229. if self.sign == -1 and other & 1:
  230. sign = -1
  231. else:
  232. sign = 1
  233. return long((ulong_powi(self.digits, other), sign))
  234. def __lshift__(self, other: int):
  235. assert type(other) is int and other >= 0
  236. x = self.digits.copy()
  237. q, r = divmod(other, PyLong_SHIFT)
  238. x = [0]*q + x
  239. for _ in range(r): x = ulong_muli(x, 2)
  240. return long((x, self.sign))
  241. def __rshift__(self, other: int):
  242. assert type(other) is int and other >= 0
  243. x = self.digits.copy()
  244. q, r = divmod(other, PyLong_SHIFT)
  245. x = x[q:]
  246. if not x: return long(0)
  247. for _ in range(r): x = ulong_floordivi(x, 2)
  248. return long((x, self.sign))
  249. def __neg__(self):
  250. return long((self.digits, -self.sign))
  251. def __cmp__(self, other):
  252. if type(other) is int:
  253. other = long(other)
  254. else:
  255. assert type(other) is long
  256. if self.sign > other.sign:
  257. return 1
  258. elif self.sign < other.sign:
  259. return -1
  260. else:
  261. return ulong_cmp(self.digits, other.digits)
  262. def __eq__(self, other):
  263. return self.__cmp__(other) == 0
  264. def __lt__(self, other):
  265. return self.__cmp__(other) < 0
  266. def __le__(self, other):
  267. return self.__cmp__(other) <= 0
  268. def __gt__(self, other):
  269. return self.__cmp__(other) > 0
  270. def __ge__(self, other):
  271. return self.__cmp__(other) >= 0
  272. def __repr__(self):
  273. prefix = '-' if self.sign < 0 else ''
  274. return prefix + ulong_repr(self.digits) + 'L'