Skip to content

Commit e9ce00d

Browse files
committed
py: Implement divmod for mpz bignum.
1 parent c5029bc commit e9ce00d

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

py/objint_mpz.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,17 @@ mp_obj_t mp_obj_int_binary_op(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
262262
mpz_pow_inpl(&res->mpz, zlhs, zrhs);
263263
break;
264264

265+
case MP_BINARY_OP_DIVMOD: {
266+
mp_obj_int_t *quo = mp_obj_int_new_mpz();
267+
mpz_divmod_inpl(&quo->mpz, &res->mpz, zlhs, zrhs);
268+
// Check signs and do Python style modulo
269+
if (zlhs->neg != zrhs->neg) {
270+
mpz_add_inpl(&res->mpz, &res->mpz, zrhs);
271+
}
272+
mp_obj_t tuple[2] = {quo, res};
273+
return mp_obj_new_tuple(2, tuple);
274+
}
275+
265276
default:
266277
return MP_OBJ_NULL; // op not supported
267278
}

tests/basics/builtin_divmod.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,9 @@
1414
except TypeError:
1515
print("TypeError")
1616

17+
# bignum
18+
l = (1 << 65) + 123
19+
print(divmod(3, l))
20+
print(divmod(l, 5))
21+
print(divmod(l + 3, l))
22+
print(divmod(l * 20, l + 2))

0 commit comments

Comments
 (0)