Skip to content

Commit 51fab28

Browse files
committed
py: Improve mpz_and function.
This should now have correct (and optimal) behaviour.
1 parent f6e430f commit 51fab28

1 file changed

Lines changed: 5 additions & 6 deletions

File tree

py/mpz.c

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -207,17 +207,15 @@ STATIC uint mpn_sub(mpz_dig_t *idig, const mpz_dig_t *jdig, uint jlen, const mpz
207207
STATIC uint mpn_and(mpz_dig_t *idig, const mpz_dig_t *jdig, uint jlen, const mpz_dig_t *kdig, uint klen) {
208208
mpz_dig_t *oidig = idig;
209209

210-
jlen -= klen;
211-
212210
for (; klen > 0; --klen, ++idig, ++jdig, ++kdig) {
213211
*idig = *jdig & *kdig;
214212
}
215213

216214
// remove trailing zeros
217-
for (; idig > oidig && *idig == 0; --idig) {
215+
for (--idig; idig >= oidig && *idig == 0; --idig) {
218216
}
219217

220-
return idig - oidig;
218+
return idig + 1 - oidig;
221219
}
222220

223221
/* computes i = j | k
@@ -898,14 +896,15 @@ void mpz_sub_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs) {
898896
can have dest, lhs, rhs the same
899897
*/
900898
void mpz_and_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs) {
901-
if (mpn_cmp(lhs->dig, lhs->len, rhs->dig, rhs->len) < 0) {
899+
// make sure lhs has the most digits
900+
if (lhs->len < rhs->len) {
902901
const mpz_t *temp = lhs;
903902
lhs = rhs;
904903
rhs = temp;
905904
}
906905

907906
if (lhs->neg == rhs->neg) {
908-
mpz_need_dig(dest, lhs->len);
907+
mpz_need_dig(dest, rhs->len);
909908
dest->len = mpn_and(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len);
910909
} else {
911910
mpz_need_dig(dest, lhs->len);

0 commit comments

Comments
 (0)