2018-05-02 19:43:17 +00:00
|
|
|
#include "tommath_private.h"
|
2019-10-19 14:24:39 +00:00
|
|
|
#ifdef MP_DIV_3_C
|
2019-04-07 13:29:11 +00:00
|
|
|
/* LibTomMath, multiple-precision integer library -- Tom St Denis */
|
|
|
|
/* SPDX-License-Identifier: Unlicense */
|
2003-07-02 15:39:39 +00:00
|
|
|
|
|
|
|
/* divide by three (based on routine from MPI and the GMP manual) */
|
2019-05-12 22:22:18 +00:00
|
|
|
mp_err mp_div_3(const mp_int *a, mp_int *c, mp_digit *d)
|
2003-07-02 15:39:39 +00:00
|
|
|
{
|
2017-08-29 20:23:48 +00:00
|
|
|
mp_int q;
|
2019-10-29 17:41:25 +00:00
|
|
|
mp_word w;
|
2017-08-29 20:23:48 +00:00
|
|
|
mp_digit b;
|
2019-05-19 15:16:13 +00:00
|
|
|
mp_err err;
|
2019-05-12 22:22:18 +00:00
|
|
|
int ix;
|
2017-08-30 03:51:11 +00:00
|
|
|
|
2019-04-13 06:46:57 +00:00
|
|
|
/* b = 2**MP_DIGIT_BIT / 3 */
|
|
|
|
b = ((mp_word)1 << (mp_word)MP_DIGIT_BIT) / (mp_word)3;
|
2003-07-02 15:39:39 +00:00
|
|
|
|
2019-05-19 15:16:13 +00:00
|
|
|
if ((err = mp_init_size(&q, a->used)) != MP_OKAY) {
|
|
|
|
return err;
|
2017-08-29 20:23:48 +00:00
|
|
|
}
|
2017-08-30 03:51:11 +00:00
|
|
|
|
2017-08-29 20:23:48 +00:00
|
|
|
q.used = a->used;
|
|
|
|
q.sign = a->sign;
|
|
|
|
w = 0;
|
2019-10-29 17:41:25 +00:00
|
|
|
for (ix = a->used; ix --> 0;) {
|
|
|
|
mp_word t;
|
2019-04-13 06:46:57 +00:00
|
|
|
w = (w << (mp_word)MP_DIGIT_BIT) | (mp_word)a->dp[ix];
|
2003-08-05 01:24:44 +00:00
|
|
|
|
2017-10-15 17:57:12 +00:00
|
|
|
if (w >= 3u) {
|
2017-08-29 20:23:48 +00:00
|
|
|
/* multiply w by [1/3] */
|
2019-04-13 06:46:57 +00:00
|
|
|
t = (w * (mp_word)b) >> (mp_word)MP_DIGIT_BIT;
|
2003-08-05 01:24:44 +00:00
|
|
|
|
2017-08-29 20:23:48 +00:00
|
|
|
/* now subtract 3 * [w/3] from w, to get the remainder */
|
|
|
|
w -= t+t+t;
|
2003-08-05 01:24:44 +00:00
|
|
|
|
2017-08-29 20:23:48 +00:00
|
|
|
/* fixup the remainder as required since
|
|
|
|
* the optimization is not exact.
|
|
|
|
*/
|
2017-10-15 17:57:12 +00:00
|
|
|
while (w >= 3u) {
|
|
|
|
t += 1u;
|
|
|
|
w -= 3u;
|
2017-08-29 20:23:48 +00:00
|
|
|
}
|
2003-07-02 15:39:39 +00:00
|
|
|
} else {
|
2017-08-29 20:23:48 +00:00
|
|
|
t = 0;
|
2003-07-02 15:39:39 +00:00
|
|
|
}
|
|
|
|
q.dp[ix] = (mp_digit)t;
|
2017-08-29 20:23:48 +00:00
|
|
|
}
|
2003-08-05 01:24:44 +00:00
|
|
|
|
2017-08-29 20:23:48 +00:00
|
|
|
/* [optional] store the remainder */
|
|
|
|
if (d != NULL) {
|
|
|
|
*d = (mp_digit)w;
|
|
|
|
}
|
2003-08-05 01:24:44 +00:00
|
|
|
|
2017-08-29 20:23:48 +00:00
|
|
|
/* [optional] store the quotient */
|
|
|
|
if (c != NULL) {
|
|
|
|
mp_clamp(&q);
|
|
|
|
mp_exch(&q, c);
|
|
|
|
}
|
|
|
|
mp_clear(&q);
|
2017-08-30 03:51:11 +00:00
|
|
|
|
2019-10-29 17:41:25 +00:00
|
|
|
return MP_OKAY;
|
2003-07-02 15:39:39 +00:00
|
|
|
}
|
|
|
|
|
2004-10-29 22:07:18 +00:00
|
|
|
#endif
|