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 as ex:
  43. raise TypeError("bit_size(num) only supports integers, not %r" % type(num)) from ex
  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. # r = gcd(a,b) i = multiplicitive inverse of a mod b
  84. # or j = multiplicitive inverse of b mod a
  85. # Neg return values for i or j are made positive mod b or a respectively
  86. # Iterateive Version is faster and uses much less stack space
  87. x = 0
  88. y = 1
  89. lx = 1
  90. ly = 0
  91. oa = a # Remember original a/b to remove
  92. ob = b # negative values from return results
  93. while b != 0:
  94. q = a // b
  95. (a, b) = (b, a % b)
  96. (x, lx) = ((lx - (q * x)), x)
  97. (y, ly) = ((ly - (q * y)), y)
  98. if lx < 0:
  99. lx += ob # If neg wrap modulo original b
  100. if ly < 0:
  101. ly += oa # If neg wrap modulo original a
  102. return a, lx, ly # Return only positive values
  103. def inverse(x: int, n: int) -> int:
  104. """Returns the inverse of x % n under multiplication, a.k.a x^-1 (mod n)
  105. >>> inverse(7, 4)
  106. 3
  107. >>> (inverse(143, 4) * 143) % 4
  108. 1
  109. """
  110. (divider, inv, _) = extended_gcd(x, n)
  111. if divider != 1:
  112. raise NotRelativePrimeError(x, n, divider)
  113. return inv
  114. def crt(a_values: typing.Iterable[int], modulo_values: typing.Iterable[int]) -> int:
  115. """Chinese Remainder Theorem.
  116. Calculates x such that x = a[i] (mod m[i]) for each i.
  117. :param a_values: the a-values of the above equation
  118. :param modulo_values: the m-values of the above equation
  119. :returns: x such that x = a[i] (mod m[i]) for each i
  120. >>> crt([2, 3], [3, 5])
  121. 8
  122. >>> crt([2, 3, 2], [3, 5, 7])
  123. 23
  124. >>> crt([2, 3, 0], [7, 11, 15])
  125. 135
  126. """
  127. m = 1
  128. x = 0
  129. for modulo in modulo_values:
  130. m *= modulo
  131. for (m_i, a_i) in zip(modulo_values, a_values):
  132. M_i = m // m_i
  133. inv = inverse(M_i, m_i)
  134. x = (x + a_i * M_i * inv) % m
  135. return x
  136. if __name__ == "__main__":
  137. import doctest
  138. doctest.testmod()