_number_new.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. # -*- coding: ascii -*-
  2. #
  3. # Util/_number_new.py : utility functions
  4. #
  5. # Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
  6. #
  7. # ===================================================================
  8. # The contents of this file are dedicated to the public domain. To
  9. # the extent that dedication to the public domain is not available,
  10. # everyone is granted a worldwide, perpetual, royalty-free,
  11. # non-exclusive license to exercise all rights associated with the
  12. # contents of this file for any purpose whatsoever.
  13. # No rights are reserved.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  19. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  20. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  21. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. # SOFTWARE.
  23. # ===================================================================
  24. ## NOTE: Do not import this module directly. Import these functions from Crypto.Util.number.
  25. __revision__ = "$Id$"
  26. __all__ = ['ceil_shift', 'ceil_div', 'floor_div', 'exact_log2', 'exact_div']
  27. import sys
  28. if sys.version_info[0] == 2 and sys.version_info[1] == 1:
  29. from Crypto.Util.py21compat import *
  30. def ceil_shift(n, b):
  31. """Return ceil(n / 2**b) without performing any floating-point or division operations.
  32. This is done by right-shifting n by b bits and incrementing the result by 1
  33. if any '1' bits were shifted out.
  34. """
  35. if not isinstance(n, (int, long)) or not isinstance(b, (int, long)):
  36. raise TypeError("unsupported operand type(s): %r and %r" % (type(n).__name__, type(b).__name__))
  37. assert n >= 0 and b >= 0 # I haven't tested or even thought about negative values
  38. mask = (1L << b) - 1
  39. if n & mask:
  40. return (n >> b) + 1
  41. else:
  42. return n >> b
  43. def ceil_div(a, b):
  44. """Return ceil(a / b) without performing any floating-point operations."""
  45. if not isinstance(a, (int, long)) or not isinstance(b, (int, long)):
  46. raise TypeError("unsupported operand type(s): %r and %r" % (type(a).__name__, type(b).__name__))
  47. (q, r) = divmod(a, b)
  48. if r:
  49. return q + 1
  50. else:
  51. return q
  52. def floor_div(a, b):
  53. if not isinstance(a, (int, long)) or not isinstance(b, (int, long)):
  54. raise TypeError("unsupported operand type(s): %r and %r" % (type(a).__name__, type(b).__name__))
  55. (q, r) = divmod(a, b)
  56. return q
  57. def exact_log2(num):
  58. """Find and return an integer i >= 0 such that num == 2**i.
  59. If no such integer exists, this function raises ValueError.
  60. """
  61. if not isinstance(num, (int, long)):
  62. raise TypeError("unsupported operand type: %r" % (type(num).__name__,))
  63. n = long(num)
  64. if n <= 0:
  65. raise ValueError("cannot compute logarithm of non-positive number")
  66. i = 0
  67. while n != 0:
  68. if (n & 1) and n != 1:
  69. raise ValueError("No solution could be found")
  70. i += 1
  71. n >>= 1
  72. i -= 1
  73. assert num == (1L << i)
  74. return i
  75. def exact_div(p, d, allow_divzero=False):
  76. """Find and return an integer n such that p == n * d
  77. If no such integer exists, this function raises ValueError.
  78. Both operands must be integers.
  79. If the second operand is zero, this function will raise ZeroDivisionError
  80. unless allow_divzero is true (default: False).
  81. """
  82. if not isinstance(p, (int, long)) or not isinstance(d, (int, long)):
  83. raise TypeError("unsupported operand type(s): %r and %r" % (type(p).__name__, type(d).__name__))
  84. if d == 0 and allow_divzero:
  85. n = 0
  86. if p != n * d:
  87. raise ValueError("No solution could be found")
  88. else:
  89. (n, r) = divmod(p, d)
  90. if r != 0:
  91. raise ValueError("No solution could be found")
  92. assert p == n * d
  93. return n
  94. # vim:set ts=4 sw=4 sts=4 expandtab: