bn_mp_div_3.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include <tommath.h>
  2. #ifdef BN_MP_DIV_3_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis
  4. *
  5. * LibTomMath is a library that provides multiple-precision
  6. * integer arithmetic as well as number theoretic functionality.
  7. *
  8. * The library was designed directly after the MPI library by
  9. * Michael Fromberger but has been written from scratch with
  10. * additional optimizations in place.
  11. *
  12. * The library is free for all purposes without any express
  13. * guarantee it works.
  14. *
  15. * Tom St Denis, tomstdenis@gmail.com, http://math.libtomcrypt.com
  16. */
  17. /* divide by three (based on routine from MPI and the GMP manual) */
  18. int
  19. mp_div_3 (mp_int * a, mp_int *c, mp_digit * d)
  20. {
  21. mp_int q;
  22. mp_word w, t;
  23. mp_digit b;
  24. int res, ix;
  25. /* b = 2**DIGIT_BIT / 3 */
  26. b = (((mp_word)1) << ((mp_word)DIGIT_BIT)) / ((mp_word)3);
  27. if ((res = mp_init_size(&q, a->used)) != MP_OKAY) {
  28. return res;
  29. }
  30. q.used = a->used;
  31. q.sign = a->sign;
  32. w = 0;
  33. for (ix = a->used - 1; ix >= 0; ix--) {
  34. w = (w << ((mp_word)DIGIT_BIT)) | ((mp_word)a->dp[ix]);
  35. if (w >= 3) {
  36. /* multiply w by [1/3] */
  37. t = (w * ((mp_word)b)) >> ((mp_word)DIGIT_BIT);
  38. /* now subtract 3 * [w/3] from w, to get the remainder */
  39. w -= t+t+t;
  40. /* fixup the remainder as required since
  41. * the optimization is not exact.
  42. */
  43. while (w >= 3) {
  44. t += 1;
  45. w -= 3;
  46. }
  47. } else {
  48. t = 0;
  49. }
  50. q.dp[ix] = (mp_digit)t;
  51. }
  52. /* [optional] store the remainder */
  53. if (d != NULL) {
  54. *d = (mp_digit)w;
  55. }
  56. /* [optional] store the quotient */
  57. if (c != NULL) {
  58. mp_clamp(&q);
  59. mp_exch(&q, c);
  60. }
  61. mp_clear(&q);
  62. return res;
  63. }
  64. #endif
  65. /* $Source: /cvs/libtom/libtommath/bn_mp_div_3.c,v $ */
  66. /* $Revision: 1.3 $ */
  67. /* $Date: 2006/03/31 14:18:44 $ */