reciprocal.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. Copyright (c) 2018-2019, tevador <tevador@gmail.com>
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. * Redistributions of source code must retain the above copyright
  7. notice, this list of conditions and the following disclaimer.
  8. * Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. * Neither the name of the copyright holder nor the
  12. names of its contributors may be used to endorse or promote products
  13. derived from this software without specific prior written permission.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  15. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  16. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  17. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  18. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  19. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  20. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  21. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  22. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  23. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. */
  25. #include <assert.h>
  26. #include "reciprocal.h"
  27. /*
  28. Calculates rcp = 2**x / divisor for highest integer x such that rcp < 2**64.
  29. divisor must not be 0 or a power of 2
  30. Equivalent x86 assembly (divisor in rcx):
  31. mov edx, 1
  32. mov r8, rcx
  33. xor eax, eax
  34. bsr rcx, rcx
  35. shl rdx, cl
  36. div r8
  37. ret
  38. */
  39. uint64_t randomx_reciprocal(uint64_t divisor) {
  40. assert(divisor != 0);
  41. const uint64_t p2exp63 = 1ULL << 63;
  42. uint64_t quotient = p2exp63 / divisor, remainder = p2exp63 % divisor;
  43. unsigned bsr = 0; //highest set bit in divisor
  44. for (uint64_t bit = divisor; bit > 0; bit >>= 1)
  45. bsr++;
  46. for (unsigned shift = 0; shift < bsr; shift++) {
  47. if (remainder >= divisor - remainder) {
  48. quotient = quotient * 2 + 1;
  49. remainder = remainder * 2 - divisor;
  50. }
  51. else {
  52. quotient = quotient * 2;
  53. remainder = remainder * 2;
  54. }
  55. }
  56. return quotient;
  57. }
  58. #if !RANDOMX_HAVE_FAST_RECIPROCAL
  59. uint64_t randomx_reciprocal_fast(uint64_t divisor) {
  60. return randomx_reciprocal(divisor);
  61. }
  62. #endif