_long.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 str:
  153. self.digits, self.sign = ulong_fromstr(x)
  154. else:
  155. raise TypeError('expected int or str')
  156. def __add__(self, other):
  157. if type(other) is int:
  158. other = long(other)
  159. elif type(other) is not long:
  160. return NotImplemented
  161. if self.sign == other.sign:
  162. return long((ulong_add(self.digits, other.digits), self.sign))
  163. else:
  164. cmp = ulong_cmp(self.digits, other.digits)
  165. if cmp == 0:
  166. return long(0)
  167. if cmp > 0:
  168. return long((ulong_sub(self.digits, other.digits), self.sign))
  169. else:
  170. return long((ulong_sub(other.digits, self.digits), other.sign))
  171. def __radd__(self, other):
  172. return self.__add__(other)
  173. def __sub__(self, other):
  174. if type(other) is int:
  175. other = long(other)
  176. elif type(other) is not long:
  177. return NotImplemented
  178. if self.sign != other.sign:
  179. return long((ulong_add(self.digits, other.digits), self.sign))
  180. cmp = ulong_cmp(self.digits, other.digits)
  181. if cmp == 0:
  182. return long(0)
  183. if cmp > 0:
  184. return long((ulong_sub(self.digits, other.digits), self.sign))
  185. else:
  186. return long((ulong_sub(other.digits, self.digits), -other.sign))
  187. def __rsub__(self, other):
  188. if type(other) is int:
  189. other = long(other)
  190. elif type(other) is not long:
  191. return NotImplemented
  192. return other.__sub__(self)
  193. def __mul__(self, other):
  194. if type(other) is int:
  195. return long((
  196. ulong_muli(self.digits, abs(other)),
  197. self.sign * (1 if other >= 0 else -1)
  198. ))
  199. elif type(other) is long:
  200. return long((
  201. ulong_mul(self.digits, other.digits),
  202. self.sign * other.sign
  203. ))
  204. return NotImplemented
  205. def __rmul__(self, other):
  206. return self.__mul__(other)
  207. #######################################################
  208. def __divmod__(self, other: int):
  209. assert type(other) is int and other > 0
  210. assert self.sign == 1
  211. q, r = ulong_divmodi(self.digits, other)
  212. return long((q, 1)), r
  213. def __floordiv__(self, other: int):
  214. return self.__divmod__(other)[0]
  215. def __mod__(self, other: int):
  216. return self.__divmod__(other)[1]
  217. def __pow__(self, other: int):
  218. assert type(other) is int and other >= 0
  219. if self.sign == -1 and other & 1:
  220. sign = -1
  221. else:
  222. sign = 1
  223. return long((ulong_powi(self.digits, other), sign))
  224. def __lshift__(self, other: int):
  225. # TODO: optimize
  226. assert type(other) is int and other >= 0
  227. x = self.digits.copy()
  228. for _ in range(other):
  229. x = ulong_muli(x, 2)
  230. return long((x, self.sign))
  231. def __rshift__(self, other: int):
  232. # TODO: optimize
  233. assert type(other) is int and other >= 0
  234. x = self.digits.copy()
  235. for _ in range(other):
  236. x = ulong_floordivi(x, 2)
  237. return long((x, self.sign))
  238. def __and__(self, other):
  239. raise NotImplementedError
  240. def __or__(self, other):
  241. raise NotImplementedError
  242. def __xor__(self, other):
  243. raise NotImplementedError
  244. def __neg__(self):
  245. return long((self.digits, -self.sign))
  246. def __cmp__(self, other):
  247. if type(other) is int:
  248. other = long(other)
  249. else:
  250. assert type(other) is long
  251. if self.sign > other.sign:
  252. return 1
  253. elif self.sign < other.sign:
  254. return -1
  255. else:
  256. return ulong_cmp(self.digits, other.digits)
  257. def __eq__(self, other):
  258. return self.__cmp__(other) == 0
  259. def __lt__(self, other):
  260. return self.__cmp__(other) < 0
  261. def __le__(self, other):
  262. return self.__cmp__(other) <= 0
  263. def __gt__(self, other):
  264. return self.__cmp__(other) > 0
  265. def __ge__(self, other):
  266. return self.__cmp__(other) >= 0
  267. def __repr__(self):
  268. prefix = '-' if self.sign < 0 else ''
  269. return prefix + ulong_repr(self.digits) + 'L'