1
0

_long.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. if ulong_cmp(a, b) < 0:
  92. return [0], a
  93. if len(b) == 1:
  94. q, r = ulong_divmodi(a, b[0])
  95. r, _ = ulong_fromint(r)
  96. return q, r
  97. max = (len(a) - len(b)) * PyLong_SHIFT + \
  98. (a[-1].bit_length() - b[-1].bit_length())
  99. low = [0]
  100. high = (max // PyLong_SHIFT) * [0] + \
  101. [(2**(max % PyLong_SHIFT)) & PyLong_MASK]
  102. while ulong_cmp(low, high) < 0:
  103. ulong_inc_(high)
  104. mid, r = ulong_divmodi(ulong_add(low, high), 2)
  105. if ulong_cmp(a, ulong_mul(b, mid)) >= 0:
  106. low = mid
  107. else:
  108. high = ulong_sub(mid, [1])
  109. q = [0] * (len(a) - len(b) + 1)
  110. while ulong_cmp(a, ulong_mul(b, low)) >= 0:
  111. q = ulong_add(q, low)
  112. a = ulong_sub(a, ulong_mul(b, low))
  113. ulong_unpad_(q)
  114. return q, a
  115. def ulong_floordivi(a: list, b: int):
  116. # b > 0
  117. return ulong_divmodi(a, b)[0]
  118. def ulong_muli(a: list, b: int):
  119. # b >= 0
  120. res = [0] * len(a)
  121. carry = 0
  122. for i in range(len(a)):
  123. carry += a[i] * b
  124. res[i] = carry & PyLong_MASK
  125. carry >>= PyLong_SHIFT
  126. if carry > 0:
  127. res.append(carry)
  128. return res
  129. def ulong_mul(a: list, b: list):
  130. N = len(a) + len(b)
  131. # use grade-school multiplication
  132. res = [0] * N
  133. for i in range(len(a)):
  134. carry = 0
  135. for j in range(len(b)):
  136. carry += res[i+j] + a[i] * b[j]
  137. res[i+j] = carry & PyLong_MASK
  138. carry >>= PyLong_SHIFT
  139. res[i+len(b)] = carry
  140. ulong_unpad_(res)
  141. return res
  142. def ulong_powi(a: list, b: int):
  143. # b >= 0
  144. if b == 0: return [1]
  145. res = [1]
  146. while b:
  147. if b & 1:
  148. res = ulong_mul(res, a)
  149. a = ulong_mul(a, a)
  150. b >>= 1
  151. return res
  152. def ulong_repr(x: list) -> str:
  153. res = []
  154. while len(x)>1 or x[0]>0: # non-zero
  155. x, r = ulong_divmodi(x, PyLong_DECIMAL_BASE)
  156. res.append(str(r).zfill(PyLong_DECIMAL_SHIFT))
  157. res.reverse()
  158. s = ''.join(res)
  159. if len(s) == 0: return '0'
  160. if len(s) > 1: s = s.lstrip('0')
  161. return s
  162. def ulong_fromstr(s: str):
  163. if s[-1] == 'L':
  164. s = s[:-1]
  165. res, base = [0], [1]
  166. if s[0] == '-':
  167. sign = -1
  168. s = s[1:]
  169. else:
  170. sign = 1
  171. s = s[::-1]
  172. for c in s:
  173. c = ord(c) - 48
  174. assert 0 <= c <= 9
  175. res = ulong_add(res, ulong_muli(base, c))
  176. base = ulong_muli(base, 10)
  177. return res, sign
  178. class long:
  179. def __init__(self, x):
  180. if type(x) is tuple:
  181. self.digits, self.sign = x
  182. elif type(x) is int:
  183. self.digits, self.sign = ulong_fromint(x)
  184. elif type(x) is float:
  185. self.digits, self.sign = ulong_fromint(int(x))
  186. elif type(x) is str:
  187. self.digits, self.sign = ulong_fromstr(x)
  188. elif type(x) is long:
  189. self.digits, self.sign = x.digits.copy(), x.sign
  190. else:
  191. raise TypeError('expected int or str')
  192. def __len__(self):
  193. return len(self.digits)
  194. def __add__(self, other):
  195. if type(other) is int:
  196. other = long(other)
  197. elif type(other) is not long:
  198. return NotImplemented
  199. if self.sign == other.sign:
  200. return long((ulong_add(self.digits, other.digits), self.sign))
  201. else:
  202. cmp = ulong_cmp(self.digits, other.digits)
  203. if cmp == 0:
  204. return long(0)
  205. if cmp > 0:
  206. return long((ulong_sub(self.digits, other.digits), self.sign))
  207. else:
  208. return long((ulong_sub(other.digits, self.digits), other.sign))
  209. def __radd__(self, other):
  210. return self.__add__(other)
  211. def __sub__(self, other):
  212. if type(other) is int:
  213. other = long(other)
  214. elif type(other) is not long:
  215. return NotImplemented
  216. if self.sign != other.sign:
  217. return long((ulong_add(self.digits, other.digits), self.sign))
  218. cmp = ulong_cmp(self.digits, other.digits)
  219. if cmp == 0:
  220. return long(0)
  221. if cmp > 0:
  222. return long((ulong_sub(self.digits, other.digits), self.sign))
  223. else:
  224. return long((ulong_sub(other.digits, self.digits), -other.sign))
  225. def __rsub__(self, other):
  226. if type(other) is int:
  227. other = long(other)
  228. elif type(other) is not long:
  229. return NotImplemented
  230. return other.__sub__(self)
  231. def __mul__(self, other):
  232. if type(other) is int:
  233. return long((
  234. ulong_muli(self.digits, abs(other)),
  235. self.sign * (1 if other >= 0 else -1)
  236. ))
  237. elif type(other) is long:
  238. return long((
  239. ulong_mul(self.digits, other.digits),
  240. self.sign * other.sign
  241. ))
  242. return NotImplemented
  243. def __rmul__(self, other):
  244. return self.__mul__(other)
  245. #######################################################
  246. def __divmod__(self, other):
  247. if type(other) is int:
  248. assert self.sign == 1 and other > 0
  249. q, r = ulong_divmodi(self.digits, other)
  250. return long((q, 1)), r
  251. if type(other) is long:
  252. assert self.sign == 1 and other.sign == 1
  253. q, r = ulong_divmod(self.digits, other.digits)
  254. assert len(other)>1 or other.digits[0]>0
  255. return long((q, 1)), long((r, 1))
  256. raise NotImplementedError
  257. def __floordiv__(self, other):
  258. return self.__divmod__(other)[0]
  259. def __mod__(self, other):
  260. return self.__divmod__(other)[1]
  261. def __pow__(self, other: int):
  262. assert type(other) is int and other >= 0
  263. if self.sign == -1 and other & 1:
  264. sign = -1
  265. else:
  266. sign = 1
  267. return long((ulong_powi(self.digits, other), sign))
  268. def __lshift__(self, other: int):
  269. assert type(other) is int and other >= 0
  270. x = self.digits.copy()
  271. q, r = divmod(other, PyLong_SHIFT)
  272. x = [0]*q + x
  273. for _ in range(r): x = ulong_muli(x, 2)
  274. return long((x, self.sign))
  275. def __rshift__(self, other: int):
  276. assert type(other) is int and other >= 0
  277. x = self.digits.copy()
  278. q, r = divmod(other, PyLong_SHIFT)
  279. x = x[q:]
  280. if not x: return long(0)
  281. for _ in range(r): x = ulong_floordivi(x, 2)
  282. return long((x, self.sign))
  283. def __neg__(self):
  284. return long((self.digits, -self.sign))
  285. def __cmp__(self, other):
  286. if type(other) is int:
  287. other = long(other)
  288. elif type(other) is not long:
  289. return NotImplemented
  290. if self.sign > other.sign:
  291. return 1
  292. elif self.sign < other.sign:
  293. return -1
  294. else:
  295. return ulong_cmp(self.digits, other.digits)
  296. def __eq__(self, other):
  297. return self.__cmp__(other) == 0
  298. def __lt__(self, other):
  299. return self.__cmp__(other) < 0
  300. def __le__(self, other):
  301. return self.__cmp__(other) <= 0
  302. def __gt__(self, other):
  303. return self.__cmp__(other) > 0
  304. def __ge__(self, other):
  305. return self.__cmp__(other) >= 0
  306. def __repr__(self):
  307. prefix = '-' if self.sign < 0 else ''
  308. return prefix + ulong_repr(self.digits) + 'L'