_long.py 8.9 KB

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