Skip to content

Commit 65402ab

Browse files
committed
py/mpz: Do Python style division/modulo within bignum divmod routine.
This patch consolidates the Python logic for division/modulo to one place within the bignum code.
1 parent dc3faea commit 65402ab

3 files changed

Lines changed: 8 additions & 16 deletions

File tree

py/mpz.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1509,8 +1509,14 @@ void mpz_divmod_inpl(mpz_t *dest_quo, mpz_t *dest_rem, const mpz_t *lhs, const m
15091509
//rhs->dig[rhs->len] = 0;
15101510
mpn_div(dest_rem->dig, &dest_rem->len, rhs->dig, rhs->len, dest_quo->dig, &dest_quo->len);
15111511

1512+
// check signs and do Python style modulo
15121513
if (lhs->neg != rhs->neg) {
15131514
dest_quo->neg = 1;
1515+
if (!mpz_is_zero(dest_rem)) {
1516+
mpz_t mpzone; mpz_init_from_int(&mpzone, -1);
1517+
mpz_add_inpl(dest_quo, dest_quo, &mpzone);
1518+
mpz_add_inpl(dest_rem, dest_rem, rhs);
1519+
}
15141520
}
15151521
}
15161522

py/objint_mpz.c

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -239,12 +239,6 @@ mp_obj_t mp_obj_int_binary_op(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
239239
}
240240
mpz_t rem; mpz_init_zero(&rem);
241241
mpz_divmod_inpl(&res->mpz, &rem, zlhs, zrhs);
242-
if (zlhs->neg != zrhs->neg) {
243-
if (!mpz_is_zero(&rem)) {
244-
mpz_t mpzone; mpz_init_from_int(&mpzone, -1);
245-
mpz_add_inpl(&res->mpz, &res->mpz, &mpzone);
246-
}
247-
}
248242
mpz_deinit(&rem);
249243
break;
250244
}
@@ -256,10 +250,6 @@ mp_obj_t mp_obj_int_binary_op(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
256250
mpz_t quo; mpz_init_zero(&quo);
257251
mpz_divmod_inpl(&quo, &res->mpz, zlhs, zrhs);
258252
mpz_deinit(&quo);
259-
// Check signs and do Python style modulo
260-
if (zlhs->neg != zrhs->neg) {
261-
mpz_add_inpl(&res->mpz, &res->mpz, zrhs);
262-
}
263253
break;
264254
}
265255

@@ -303,10 +293,6 @@ mp_obj_t mp_obj_int_binary_op(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
303293
}
304294
mp_obj_int_t *quo = mp_obj_int_new_mpz();
305295
mpz_divmod_inpl(&quo->mpz, &res->mpz, zlhs, zrhs);
306-
// Check signs and do Python style modulo
307-
if (zlhs->neg != zrhs->neg) {
308-
mpz_add_inpl(&res->mpz, &res->mpz, zrhs);
309-
}
310296
mp_obj_t tuple[2] = {MP_OBJ_FROM_PTR(quo), MP_OBJ_FROM_PTR(res)};
311297
return mp_obj_new_tuple(2, tuple);
312298
}

tests/basics/int_big_mod.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44

55
for i in range(11):
66
for j in range(11):
7-
x = delta * (i)# - 5) # TODO reinstate negative number test when % is working with sign correctly
8-
y = delta * (j)# - 5) # TODO reinstate negative number test when % is working with sign correctly
7+
x = delta * (i - 5)
8+
y = delta * (j - 5)
99
if y != 0:
1010
print(x % y)
1111

0 commit comments

Comments
 (0)