_IntegerGMP.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. #
  10. # 1. Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # 2. Redistributions in binary form must reproduce the above copyright
  13. # notice, this list of conditions and the following disclaimer in
  14. # the documentation and/or other materials provided with the
  15. # distribution.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  20. # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  21. # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  22. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  23. # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  25. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  26. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  27. # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28. # POSSIBILITY OF SUCH DAMAGE.
  29. # ===================================================================
  30. import sys
  31. from Cryptodome.Util.py3compat import tobytes, is_native_int
  32. from Cryptodome.Util._raw_api import (backend, load_lib,
  33. get_raw_buffer, get_c_string,
  34. null_pointer, create_string_buffer,
  35. c_ulong, c_size_t)
  36. from ._IntegerBase import IntegerBase
  37. gmp_defs = """typedef unsigned long UNIX_ULONG;
  38. typedef struct { int a; int b; void *c; } MPZ;
  39. typedef MPZ mpz_t[1];
  40. typedef UNIX_ULONG mp_bitcnt_t;
  41. void __gmpz_init (mpz_t x);
  42. void __gmpz_init_set (mpz_t rop, const mpz_t op);
  43. void __gmpz_init_set_ui (mpz_t rop, UNIX_ULONG op);
  44. UNIX_ULONG __gmpz_get_ui (const mpz_t op);
  45. void __gmpz_set (mpz_t rop, const mpz_t op);
  46. void __gmpz_set_ui (mpz_t rop, UNIX_ULONG op);
  47. void __gmpz_add (mpz_t rop, const mpz_t op1, const mpz_t op2);
  48. void __gmpz_add_ui (mpz_t rop, const mpz_t op1, UNIX_ULONG op2);
  49. void __gmpz_sub_ui (mpz_t rop, const mpz_t op1, UNIX_ULONG op2);
  50. void __gmpz_addmul (mpz_t rop, const mpz_t op1, const mpz_t op2);
  51. void __gmpz_addmul_ui (mpz_t rop, const mpz_t op1, UNIX_ULONG op2);
  52. void __gmpz_submul_ui (mpz_t rop, const mpz_t op1, UNIX_ULONG op2);
  53. void __gmpz_import (mpz_t rop, size_t count, int order, size_t size,
  54. int endian, size_t nails, const void *op);
  55. void * __gmpz_export (void *rop, size_t *countp, int order,
  56. size_t size,
  57. int endian, size_t nails, const mpz_t op);
  58. size_t __gmpz_sizeinbase (const mpz_t op, int base);
  59. void __gmpz_sub (mpz_t rop, const mpz_t op1, const mpz_t op2);
  60. void __gmpz_mul (mpz_t rop, const mpz_t op1, const mpz_t op2);
  61. void __gmpz_mul_ui (mpz_t rop, const mpz_t op1, UNIX_ULONG op2);
  62. int __gmpz_cmp (const mpz_t op1, const mpz_t op2);
  63. void __gmpz_powm (mpz_t rop, const mpz_t base, const mpz_t exp, const
  64. mpz_t mod);
  65. void __gmpz_powm_ui (mpz_t rop, const mpz_t base, UNIX_ULONG exp,
  66. const mpz_t mod);
  67. void __gmpz_pow_ui (mpz_t rop, const mpz_t base, UNIX_ULONG exp);
  68. void __gmpz_sqrt(mpz_t rop, const mpz_t op);
  69. void __gmpz_mod (mpz_t r, const mpz_t n, const mpz_t d);
  70. void __gmpz_neg (mpz_t rop, const mpz_t op);
  71. void __gmpz_abs (mpz_t rop, const mpz_t op);
  72. void __gmpz_and (mpz_t rop, const mpz_t op1, const mpz_t op2);
  73. void __gmpz_ior (mpz_t rop, const mpz_t op1, const mpz_t op2);
  74. void __gmpz_clear (mpz_t x);
  75. void __gmpz_tdiv_q_2exp (mpz_t q, const mpz_t n, mp_bitcnt_t b);
  76. void __gmpz_fdiv_q (mpz_t q, const mpz_t n, const mpz_t d);
  77. void __gmpz_mul_2exp (mpz_t rop, const mpz_t op1, mp_bitcnt_t op2);
  78. int __gmpz_tstbit (const mpz_t op, mp_bitcnt_t bit_index);
  79. int __gmpz_perfect_square_p (const mpz_t op);
  80. int __gmpz_jacobi (const mpz_t a, const mpz_t b);
  81. void __gmpz_gcd (mpz_t rop, const mpz_t op1, const mpz_t op2);
  82. UNIX_ULONG __gmpz_gcd_ui (mpz_t rop, const mpz_t op1,
  83. UNIX_ULONG op2);
  84. void __gmpz_lcm (mpz_t rop, const mpz_t op1, const mpz_t op2);
  85. int __gmpz_invert (mpz_t rop, const mpz_t op1, const mpz_t op2);
  86. int __gmpz_divisible_p (const mpz_t n, const mpz_t d);
  87. int __gmpz_divisible_ui_p (const mpz_t n, UNIX_ULONG d);
  88. """
  89. if sys.platform == "win32":
  90. raise ImportError("Not using GMP on Windows")
  91. lib = load_lib("gmp", gmp_defs)
  92. implementation = {"library": "gmp", "api": backend}
  93. if hasattr(lib, "__mpir_version"):
  94. raise ImportError("MPIR library detected")
  95. # In order to create a function that returns a pointer to
  96. # a new MPZ structure, we need to break the abstraction
  97. # and know exactly what ffi backend we have
  98. if implementation["api"] == "ctypes":
  99. from ctypes import Structure, c_int, c_void_p, byref
  100. class _MPZ(Structure):
  101. _fields_ = [('_mp_alloc', c_int),
  102. ('_mp_size', c_int),
  103. ('_mp_d', c_void_p)]
  104. def new_mpz():
  105. return byref(_MPZ())
  106. else:
  107. # We are using CFFI
  108. from Cryptodome.Util._raw_api import ffi
  109. def new_mpz():
  110. return ffi.new("MPZ*")
  111. # Lazy creation of GMP methods
  112. class _GMP(object):
  113. def __getattr__(self, name):
  114. if name.startswith("mpz_"):
  115. func_name = "__gmpz_" + name[4:]
  116. elif name.startswith("gmp_"):
  117. func_name = "__gmp_" + name[4:]
  118. else:
  119. raise AttributeError("Attribute %s is invalid" % name)
  120. func = getattr(lib, func_name)
  121. setattr(self, name, func)
  122. return func
  123. _gmp = _GMP()
  124. class IntegerGMP(IntegerBase):
  125. """A fast, arbitrary precision integer"""
  126. _zero_mpz_p = new_mpz()
  127. _gmp.mpz_init_set_ui(_zero_mpz_p, c_ulong(0))
  128. def __init__(self, value):
  129. """Initialize the integer to the given value."""
  130. self._mpz_p = new_mpz()
  131. self._initialized = False
  132. if isinstance(value, float):
  133. raise ValueError("A floating point type is not a natural number")
  134. self._initialized = True
  135. if is_native_int(value):
  136. _gmp.mpz_init(self._mpz_p)
  137. if value == 0:
  138. return
  139. tmp = new_mpz()
  140. _gmp.mpz_init(tmp)
  141. positive = value >= 0
  142. reduce = abs(value)
  143. slots = (reduce.bit_length() - 1) // 32 + 1
  144. while slots > 0:
  145. slots = slots - 1
  146. _gmp.mpz_set_ui(tmp,
  147. c_ulong(0xFFFFFFFF & (reduce >> (slots * 32))))
  148. _gmp.mpz_mul_2exp(tmp, tmp, c_ulong(slots * 32))
  149. _gmp.mpz_add(self._mpz_p, self._mpz_p, tmp)
  150. if not positive:
  151. _gmp.mpz_neg(self._mpz_p, self._mpz_p)
  152. elif isinstance(value, IntegerGMP):
  153. _gmp.mpz_init_set(self._mpz_p, value._mpz_p)
  154. else:
  155. raise NotImplementedError
  156. # Conversions
  157. def __int__(self):
  158. tmp = new_mpz()
  159. _gmp.mpz_init_set(tmp, self._mpz_p)
  160. value = 0
  161. slot = 0
  162. while _gmp.mpz_cmp(tmp, self._zero_mpz_p) != 0:
  163. lsb = _gmp.mpz_get_ui(tmp) & 0xFFFFFFFF
  164. value |= lsb << (slot * 32)
  165. _gmp.mpz_tdiv_q_2exp(tmp, tmp, c_ulong(32))
  166. slot = slot + 1
  167. if self < 0:
  168. value = -value
  169. return int(value)
  170. def __str__(self):
  171. return str(int(self))
  172. def __repr__(self):
  173. return "Integer(%s)" % str(self)
  174. # Only Python 2.x
  175. def __hex__(self):
  176. return hex(int(self))
  177. # Only Python 3.x
  178. def __index__(self):
  179. return int(self)
  180. def to_bytes(self, block_size=0):
  181. """Convert the number into a byte string.
  182. This method encodes the number in network order and prepends
  183. as many zero bytes as required. It only works for non-negative
  184. values.
  185. :Parameters:
  186. block_size : integer
  187. The exact size the output byte string must have.
  188. If zero, the string has the minimal length.
  189. :Returns:
  190. A byte string.
  191. :Raise ValueError:
  192. If the value is negative or if ``block_size`` is
  193. provided and the length of the byte string would exceed it.
  194. """
  195. if self < 0:
  196. raise ValueError("Conversion only valid for non-negative numbers")
  197. buf_len = (_gmp.mpz_sizeinbase(self._mpz_p, 2) + 7) // 8
  198. if buf_len > block_size > 0:
  199. raise ValueError("Number is too big to convert to byte string"
  200. " of prescribed length")
  201. buf = create_string_buffer(buf_len)
  202. _gmp.mpz_export(
  203. buf,
  204. null_pointer, # Ignore countp
  205. 1, # Big endian
  206. c_size_t(1), # Each word is 1 byte long
  207. 0, # Endianess within a word - not relevant
  208. c_size_t(0), # No nails
  209. self._mpz_p)
  210. return b'\x00' * max(0, block_size - buf_len) + get_raw_buffer(buf)
  211. @staticmethod
  212. def from_bytes(byte_string):
  213. """Convert a byte string into a number.
  214. :Parameters:
  215. byte_string : byte string
  216. The input number, encoded in network order.
  217. It can only be non-negative.
  218. :Return:
  219. The ``Integer`` object carrying the same value as the input.
  220. """
  221. result = IntegerGMP(0)
  222. _gmp.mpz_import(
  223. result._mpz_p,
  224. c_size_t(len(byte_string)), # Amount of words to read
  225. 1, # Big endian
  226. c_size_t(1), # Each word is 1 byte long
  227. 0, # Endianess within a word - not relevant
  228. c_size_t(0), # No nails
  229. byte_string)
  230. return result
  231. # Relations
  232. def _apply_and_return(self, func, term):
  233. if not isinstance(term, IntegerGMP):
  234. term = IntegerGMP(term)
  235. return func(self._mpz_p, term._mpz_p)
  236. def __eq__(self, term):
  237. if not (isinstance(term, IntegerGMP) or is_native_int(term)):
  238. return False
  239. return self._apply_and_return(_gmp.mpz_cmp, term) == 0
  240. def __ne__(self, term):
  241. if not (isinstance(term, IntegerGMP) or is_native_int(term)):
  242. return True
  243. return self._apply_and_return(_gmp.mpz_cmp, term) != 0
  244. def __lt__(self, term):
  245. return self._apply_and_return(_gmp.mpz_cmp, term) < 0
  246. def __le__(self, term):
  247. return self._apply_and_return(_gmp.mpz_cmp, term) <= 0
  248. def __gt__(self, term):
  249. return self._apply_and_return(_gmp.mpz_cmp, term) > 0
  250. def __ge__(self, term):
  251. return self._apply_and_return(_gmp.mpz_cmp, term) >= 0
  252. def __nonzero__(self):
  253. return _gmp.mpz_cmp(self._mpz_p, self._zero_mpz_p) != 0
  254. __bool__ = __nonzero__
  255. def is_negative(self):
  256. return _gmp.mpz_cmp(self._mpz_p, self._zero_mpz_p) < 0
  257. # Arithmetic operations
  258. def __add__(self, term):
  259. result = IntegerGMP(0)
  260. if not isinstance(term, IntegerGMP):
  261. try:
  262. term = IntegerGMP(term)
  263. except NotImplementedError:
  264. return NotImplemented
  265. _gmp.mpz_add(result._mpz_p,
  266. self._mpz_p,
  267. term._mpz_p)
  268. return result
  269. def __sub__(self, term):
  270. result = IntegerGMP(0)
  271. if not isinstance(term, IntegerGMP):
  272. try:
  273. term = IntegerGMP(term)
  274. except NotImplementedError:
  275. return NotImplemented
  276. _gmp.mpz_sub(result._mpz_p,
  277. self._mpz_p,
  278. term._mpz_p)
  279. return result
  280. def __mul__(self, term):
  281. result = IntegerGMP(0)
  282. if not isinstance(term, IntegerGMP):
  283. try:
  284. term = IntegerGMP(term)
  285. except NotImplementedError:
  286. return NotImplemented
  287. _gmp.mpz_mul(result._mpz_p,
  288. self._mpz_p,
  289. term._mpz_p)
  290. return result
  291. def __floordiv__(self, divisor):
  292. if not isinstance(divisor, IntegerGMP):
  293. divisor = IntegerGMP(divisor)
  294. if _gmp.mpz_cmp(divisor._mpz_p,
  295. self._zero_mpz_p) == 0:
  296. raise ZeroDivisionError("Division by zero")
  297. result = IntegerGMP(0)
  298. _gmp.mpz_fdiv_q(result._mpz_p,
  299. self._mpz_p,
  300. divisor._mpz_p)
  301. return result
  302. def __mod__(self, divisor):
  303. if not isinstance(divisor, IntegerGMP):
  304. divisor = IntegerGMP(divisor)
  305. comp = _gmp.mpz_cmp(divisor._mpz_p,
  306. self._zero_mpz_p)
  307. if comp == 0:
  308. raise ZeroDivisionError("Division by zero")
  309. if comp < 0:
  310. raise ValueError("Modulus must be positive")
  311. result = IntegerGMP(0)
  312. _gmp.mpz_mod(result._mpz_p,
  313. self._mpz_p,
  314. divisor._mpz_p)
  315. return result
  316. def inplace_pow(self, exponent, modulus=None):
  317. if modulus is None:
  318. if exponent < 0:
  319. raise ValueError("Exponent must not be negative")
  320. # Normal exponentiation
  321. if exponent > 256:
  322. raise ValueError("Exponent is too big")
  323. _gmp.mpz_pow_ui(self._mpz_p,
  324. self._mpz_p, # Base
  325. c_ulong(int(exponent))
  326. )
  327. else:
  328. # Modular exponentiation
  329. if not isinstance(modulus, IntegerGMP):
  330. modulus = IntegerGMP(modulus)
  331. if not modulus:
  332. raise ZeroDivisionError("Division by zero")
  333. if modulus.is_negative():
  334. raise ValueError("Modulus must be positive")
  335. if is_native_int(exponent):
  336. if exponent < 0:
  337. raise ValueError("Exponent must not be negative")
  338. if exponent < 65536:
  339. _gmp.mpz_powm_ui(self._mpz_p,
  340. self._mpz_p,
  341. c_ulong(exponent),
  342. modulus._mpz_p)
  343. return self
  344. exponent = IntegerGMP(exponent)
  345. elif exponent.is_negative():
  346. raise ValueError("Exponent must not be negative")
  347. _gmp.mpz_powm(self._mpz_p,
  348. self._mpz_p,
  349. exponent._mpz_p,
  350. modulus._mpz_p)
  351. return self
  352. def __pow__(self, exponent, modulus=None):
  353. result = IntegerGMP(self)
  354. return result.inplace_pow(exponent, modulus)
  355. def __abs__(self):
  356. result = IntegerGMP(0)
  357. _gmp.mpz_abs(result._mpz_p, self._mpz_p)
  358. return result
  359. def sqrt(self, modulus=None):
  360. """Return the largest Integer that does not
  361. exceed the square root"""
  362. if modulus is None:
  363. if self < 0:
  364. raise ValueError("Square root of negative value")
  365. result = IntegerGMP(0)
  366. _gmp.mpz_sqrt(result._mpz_p,
  367. self._mpz_p)
  368. else:
  369. if modulus <= 0:
  370. raise ValueError("Modulus must be positive")
  371. modulus = int(modulus)
  372. result = IntegerGMP(self._tonelli_shanks(int(self) % modulus, modulus))
  373. return result
  374. def __iadd__(self, term):
  375. if is_native_int(term):
  376. if 0 <= term < 65536:
  377. _gmp.mpz_add_ui(self._mpz_p,
  378. self._mpz_p,
  379. c_ulong(term))
  380. return self
  381. if -65535 < term < 0:
  382. _gmp.mpz_sub_ui(self._mpz_p,
  383. self._mpz_p,
  384. c_ulong(-term))
  385. return self
  386. term = IntegerGMP(term)
  387. _gmp.mpz_add(self._mpz_p,
  388. self._mpz_p,
  389. term._mpz_p)
  390. return self
  391. def __isub__(self, term):
  392. if is_native_int(term):
  393. if 0 <= term < 65536:
  394. _gmp.mpz_sub_ui(self._mpz_p,
  395. self._mpz_p,
  396. c_ulong(term))
  397. return self
  398. if -65535 < term < 0:
  399. _gmp.mpz_add_ui(self._mpz_p,
  400. self._mpz_p,
  401. c_ulong(-term))
  402. return self
  403. term = IntegerGMP(term)
  404. _gmp.mpz_sub(self._mpz_p,
  405. self._mpz_p,
  406. term._mpz_p)
  407. return self
  408. def __imul__(self, term):
  409. if is_native_int(term):
  410. if 0 <= term < 65536:
  411. _gmp.mpz_mul_ui(self._mpz_p,
  412. self._mpz_p,
  413. c_ulong(term))
  414. return self
  415. if -65535 < term < 0:
  416. _gmp.mpz_mul_ui(self._mpz_p,
  417. self._mpz_p,
  418. c_ulong(-term))
  419. _gmp.mpz_neg(self._mpz_p, self._mpz_p)
  420. return self
  421. term = IntegerGMP(term)
  422. _gmp.mpz_mul(self._mpz_p,
  423. self._mpz_p,
  424. term._mpz_p)
  425. return self
  426. def __imod__(self, divisor):
  427. if not isinstance(divisor, IntegerGMP):
  428. divisor = IntegerGMP(divisor)
  429. comp = _gmp.mpz_cmp(divisor._mpz_p,
  430. divisor._zero_mpz_p)
  431. if comp == 0:
  432. raise ZeroDivisionError("Division by zero")
  433. if comp < 0:
  434. raise ValueError("Modulus must be positive")
  435. _gmp.mpz_mod(self._mpz_p,
  436. self._mpz_p,
  437. divisor._mpz_p)
  438. return self
  439. # Boolean/bit operations
  440. def __and__(self, term):
  441. result = IntegerGMP(0)
  442. if not isinstance(term, IntegerGMP):
  443. term = IntegerGMP(term)
  444. _gmp.mpz_and(result._mpz_p,
  445. self._mpz_p,
  446. term._mpz_p)
  447. return result
  448. def __or__(self, term):
  449. result = IntegerGMP(0)
  450. if not isinstance(term, IntegerGMP):
  451. term = IntegerGMP(term)
  452. _gmp.mpz_ior(result._mpz_p,
  453. self._mpz_p,
  454. term._mpz_p)
  455. return result
  456. def __rshift__(self, pos):
  457. result = IntegerGMP(0)
  458. if pos < 0:
  459. raise ValueError("negative shift count")
  460. if pos > 65536:
  461. if self < 0:
  462. return -1
  463. else:
  464. return 0
  465. _gmp.mpz_tdiv_q_2exp(result._mpz_p,
  466. self._mpz_p,
  467. c_ulong(int(pos)))
  468. return result
  469. def __irshift__(self, pos):
  470. if pos < 0:
  471. raise ValueError("negative shift count")
  472. if pos > 65536:
  473. if self < 0:
  474. return -1
  475. else:
  476. return 0
  477. _gmp.mpz_tdiv_q_2exp(self._mpz_p,
  478. self._mpz_p,
  479. c_ulong(int(pos)))
  480. return self
  481. def __lshift__(self, pos):
  482. result = IntegerGMP(0)
  483. if not 0 <= pos < 65536:
  484. raise ValueError("Incorrect shift count")
  485. _gmp.mpz_mul_2exp(result._mpz_p,
  486. self._mpz_p,
  487. c_ulong(int(pos)))
  488. return result
  489. def __ilshift__(self, pos):
  490. if not 0 <= pos < 65536:
  491. raise ValueError("Incorrect shift count")
  492. _gmp.mpz_mul_2exp(self._mpz_p,
  493. self._mpz_p,
  494. c_ulong(int(pos)))
  495. return self
  496. def get_bit(self, n):
  497. """Return True if the n-th bit is set to 1.
  498. Bit 0 is the least significant."""
  499. if self < 0:
  500. raise ValueError("no bit representation for negative values")
  501. if n < 0:
  502. raise ValueError("negative bit count")
  503. if n > 65536:
  504. return 0
  505. return bool(_gmp.mpz_tstbit(self._mpz_p,
  506. c_ulong(int(n))))
  507. # Extra
  508. def is_odd(self):
  509. return _gmp.mpz_tstbit(self._mpz_p, 0) == 1
  510. def is_even(self):
  511. return _gmp.mpz_tstbit(self._mpz_p, 0) == 0
  512. def size_in_bits(self):
  513. """Return the minimum number of bits that can encode the number."""
  514. if self < 0:
  515. raise ValueError("Conversion only valid for non-negative numbers")
  516. return _gmp.mpz_sizeinbase(self._mpz_p, 2)
  517. def size_in_bytes(self):
  518. """Return the minimum number of bytes that can encode the number."""
  519. return (self.size_in_bits() - 1) // 8 + 1
  520. def is_perfect_square(self):
  521. return _gmp.mpz_perfect_square_p(self._mpz_p) != 0
  522. def fail_if_divisible_by(self, small_prime):
  523. """Raise an exception if the small prime is a divisor."""
  524. if is_native_int(small_prime):
  525. if 0 < small_prime < 65536:
  526. if _gmp.mpz_divisible_ui_p(self._mpz_p,
  527. c_ulong(small_prime)):
  528. raise ValueError("The value is composite")
  529. return
  530. small_prime = IntegerGMP(small_prime)
  531. if _gmp.mpz_divisible_p(self._mpz_p,
  532. small_prime._mpz_p):
  533. raise ValueError("The value is composite")
  534. def multiply_accumulate(self, a, b):
  535. """Increment the number by the product of a and b."""
  536. if not isinstance(a, IntegerGMP):
  537. a = IntegerGMP(a)
  538. if is_native_int(b):
  539. if 0 < b < 65536:
  540. _gmp.mpz_addmul_ui(self._mpz_p,
  541. a._mpz_p,
  542. c_ulong(b))
  543. return self
  544. if -65535 < b < 0:
  545. _gmp.mpz_submul_ui(self._mpz_p,
  546. a._mpz_p,
  547. c_ulong(-b))
  548. return self
  549. b = IntegerGMP(b)
  550. _gmp.mpz_addmul(self._mpz_p,
  551. a._mpz_p,
  552. b._mpz_p)
  553. return self
  554. def set(self, source):
  555. """Set the Integer to have the given value"""
  556. if not isinstance(source, IntegerGMP):
  557. source = IntegerGMP(source)
  558. _gmp.mpz_set(self._mpz_p,
  559. source._mpz_p)
  560. return self
  561. def inplace_inverse(self, modulus):
  562. """Compute the inverse of this number in the ring of
  563. modulo integers.
  564. Raise an exception if no inverse exists.
  565. """
  566. if not isinstance(modulus, IntegerGMP):
  567. modulus = IntegerGMP(modulus)
  568. comp = _gmp.mpz_cmp(modulus._mpz_p,
  569. self._zero_mpz_p)
  570. if comp == 0:
  571. raise ZeroDivisionError("Modulus cannot be zero")
  572. if comp < 0:
  573. raise ValueError("Modulus must be positive")
  574. result = _gmp.mpz_invert(self._mpz_p,
  575. self._mpz_p,
  576. modulus._mpz_p)
  577. if not result:
  578. raise ValueError("No inverse value can be computed")
  579. return self
  580. def inverse(self, modulus):
  581. result = IntegerGMP(self)
  582. result.inplace_inverse(modulus)
  583. return result
  584. def gcd(self, term):
  585. """Compute the greatest common denominator between this
  586. number and another term."""
  587. result = IntegerGMP(0)
  588. if is_native_int(term):
  589. if 0 < term < 65535:
  590. _gmp.mpz_gcd_ui(result._mpz_p,
  591. self._mpz_p,
  592. c_ulong(term))
  593. return result
  594. term = IntegerGMP(term)
  595. _gmp.mpz_gcd(result._mpz_p, self._mpz_p, term._mpz_p)
  596. return result
  597. def lcm(self, term):
  598. """Compute the least common multiplier between this
  599. number and another term."""
  600. result = IntegerGMP(0)
  601. if not isinstance(term, IntegerGMP):
  602. term = IntegerGMP(term)
  603. _gmp.mpz_lcm(result._mpz_p, self._mpz_p, term._mpz_p)
  604. return result
  605. @staticmethod
  606. def jacobi_symbol(a, n):
  607. """Compute the Jacobi symbol"""
  608. if not isinstance(a, IntegerGMP):
  609. a = IntegerGMP(a)
  610. if not isinstance(n, IntegerGMP):
  611. n = IntegerGMP(n)
  612. if n <= 0 or n.is_even():
  613. raise ValueError("n must be positive even for the Jacobi symbol")
  614. return _gmp.mpz_jacobi(a._mpz_p, n._mpz_p)
  615. # Clean-up
  616. def __del__(self):
  617. try:
  618. if self._mpz_p is not None:
  619. if self._initialized:
  620. _gmp.mpz_clear(self._mpz_p)
  621. self._mpz_p = None
  622. except AttributeError:
  623. pass