You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

185 lines
4.6 KiB

  1. # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # https://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Common functionality shared by several modules."""
  15. import typing
  16. class NotRelativePrimeError(ValueError):
  17. def __init__(self, a: int, b: int, d: int, msg: str = '') -> None:
  18. super().__init__(msg or "%d and %d are not relatively prime, divider=%i" % (a, b, d))
  19. self.a = a
  20. self.b = b
  21. self.d = d
  22. def bit_size(num: int) -> int:
  23. """
  24. Number of bits needed to represent a integer excluding any prefix
  25. 0 bits.
  26. Usage::
  27. >>> bit_size(1023)
  28. 10
  29. >>> bit_size(1024)
  30. 11
  31. >>> bit_size(1025)
  32. 11
  33. :param num:
  34. Integer value. If num is 0, returns 0. Only the absolute value of the
  35. number is considered. Therefore, signed integers will be abs(num)
  36. before the number's bit length is determined.
  37. :returns:
  38. Returns the number of bits in the integer.
  39. """
  40. try:
  41. return num.bit_length()
  42. except AttributeError:
  43. raise TypeError('bit_size(num) only supports integers, not %r' % type(num))
  44. def byte_size(number: int) -> int:
  45. """
  46. Returns the number of bytes required to hold a specific long number.
  47. The number of bytes is rounded up.
  48. Usage::
  49. >>> byte_size(1 << 1023)
  50. 128
  51. >>> byte_size((1 << 1024) - 1)
  52. 128
  53. >>> byte_size(1 << 1024)
  54. 129
  55. :param number:
  56. An unsigned integer
  57. :returns:
  58. The number of bytes required to hold a specific long number.
  59. """
  60. if number == 0:
  61. return 1
  62. return ceil_div(bit_size(number), 8)
  63. def ceil_div(num: int, div: int) -> int:
  64. """
  65. Returns the ceiling function of a division between `num` and `div`.
  66. Usage::
  67. >>> ceil_div(100, 7)
  68. 15
  69. >>> ceil_div(100, 10)
  70. 10
  71. >>> ceil_div(1, 4)
  72. 1
  73. :param num: Division's numerator, a number
  74. :param div: Division's divisor, a number
  75. :return: Rounded up result of the division between the parameters.
  76. """
  77. quanta, mod = divmod(num, div)
  78. if mod:
  79. quanta += 1
  80. return quanta
  81. def extended_gcd(a: int, b: int) -> typing.Tuple[int, int, int]:
  82. """Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb
  83. """
  84. # r = gcd(a,b) i = multiplicitive inverse of a mod b
  85. # or j = multiplicitive inverse of b mod a
  86. # Neg return values for i or j are made positive mod b or a respectively
  87. # Iterateive Version is faster and uses much less stack space
  88. x = 0
  89. y = 1
  90. lx = 1
  91. ly = 0
  92. oa = a # Remember original a/b to remove
  93. ob = b # negative values from return results
  94. while b != 0:
  95. q = a // b
  96. (a, b) = (b, a % b)
  97. (x, lx) = ((lx - (q * x)), x)
  98. (y, ly) = ((ly - (q * y)), y)
  99. if lx < 0:
  100. lx += ob # If neg wrap modulo orignal b
  101. if ly < 0:
  102. ly += oa # If neg wrap modulo orignal a
  103. return a, lx, ly # Return only positive values
  104. def inverse(x: int, n: int) -> int:
  105. """Returns the inverse of x % n under multiplication, a.k.a x^-1 (mod n)
  106. >>> inverse(7, 4)
  107. 3
  108. >>> (inverse(143, 4) * 143) % 4
  109. 1
  110. """
  111. (divider, inv, _) = extended_gcd(x, n)
  112. if divider != 1:
  113. raise NotRelativePrimeError(x, n, divider)
  114. return inv
  115. def crt(a_values: typing.Iterable[int], modulo_values: typing.Iterable[int]) -> int:
  116. """Chinese Remainder Theorem.
  117. Calculates x such that x = a[i] (mod m[i]) for each i.
  118. :param a_values: the a-values of the above equation
  119. :param modulo_values: the m-values of the above equation
  120. :returns: x such that x = a[i] (mod m[i]) for each i
  121. >>> crt([2, 3], [3, 5])
  122. 8
  123. >>> crt([2, 3, 2], [3, 5, 7])
  124. 23
  125. >>> crt([2, 3, 0], [7, 11, 15])
  126. 135
  127. """
  128. m = 1
  129. x = 0
  130. for modulo in modulo_values:
  131. m *= modulo
  132. for (m_i, a_i) in zip(modulo_values, a_values):
  133. M_i = m // m_i
  134. inv = inverse(M_i, m_i)
  135. x = (x + a_i * M_i * inv) % m
  136. return x
  137. if __name__ == '__main__':
  138. import doctest
  139. doctest.testmod()