Fix division and modulo for very large negative numbers (#1790)

This commit is contained in:
Rangi
2025-08-11 20:46:47 -04:00
committed by GitHub
parent 30a8503dcd
commit 7df9c12a6c
5 changed files with 91 additions and 10 deletions

View File

@@ -11,15 +11,16 @@
int32_t op_divide(int32_t dividend, int32_t divisor) {
// Adjust division to floor toward negative infinity,
// not truncate toward zero
return dividend / divisor - ((dividend % divisor < 0) != (divisor < 0));
int32_t remainder = dividend % divisor;
return dividend / divisor - (remainder != 0 && (remainder < 0) != (divisor < 0));
}
int32_t op_modulo(int32_t dividend, int32_t divisor) {
int32_t remainder = dividend % divisor;
// Adjust modulo to have the sign of the divisor,
// not the sign of the dividend
return remainder + divisor * ((remainder < 0) != (divisor < 0));
return static_cast<int32_t>(
dividend - static_cast<int64_t>(op_divide(dividend, divisor)) * divisor
);
}
int32_t op_exponent(int32_t base, uint32_t power) {