_long.py 8.3 KB

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