bn_mp_div_3.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "tommath_private.h"
  2. #ifdef BN_MP_DIV_3_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis */
  4. /* SPDX-License-Identifier: Unlicense */
  5. /* divide by three (based on routine from MPI and the GMP manual) */
  6. mp_err mp_div_3(const mp_int *a, mp_int *c, mp_digit *d)
  7. {
  8. mp_int q;
  9. mp_word w, t;
  10. mp_digit b;
  11. mp_err err;
  12. int ix;
  13. /* b = 2**MP_DIGIT_BIT / 3 */
  14. b = ((mp_word)1 << (mp_word)MP_DIGIT_BIT) / (mp_word)3;
  15. if ((err = mp_init_size(&q, a->used)) != MP_OKAY) {
  16. return err;
  17. }
  18. q.used = a->used;
  19. q.sign = a->sign;
  20. w = 0;
  21. for (ix = a->used - 1; ix >= 0; ix--) {
  22. w = (w << (mp_word)MP_DIGIT_BIT) | (mp_word)a->dp[ix];
  23. if (w >= 3u) {
  24. /* multiply w by [1/3] */
  25. t = (w * (mp_word)b) >> (mp_word)MP_DIGIT_BIT;
  26. /* now subtract 3 * [w/3] from w, to get the remainder */
  27. w -= t+t+t;
  28. /* fixup the remainder as required since
  29. * the optimization is not exact.
  30. */
  31. while (w >= 3u) {
  32. t += 1u;
  33. w -= 3u;
  34. }
  35. } else {
  36. t = 0;
  37. }
  38. q.dp[ix] = (mp_digit)t;
  39. }
  40. /* [optional] store the remainder */
  41. if (d != NULL) {
  42. *d = (mp_digit)w;
  43. }
  44. /* [optional] store the quotient */
  45. if (c != NULL) {
  46. mp_clamp(&q);
  47. mp_exch(&q, c);
  48. }
  49. mp_clear(&q);
  50. return err;
  51. }
  52. #endif