Skip to content

Commit 029564b

Browse files
authored
math.big: respect the sign of the dividend in % operator, add test (#24489)
1 parent 7ecc175 commit 029564b

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

vlib/math/big/big_test.v

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -639,6 +639,19 @@ fn test_mod() {
639639
}
640640
}
641641

642+
fn test_mod_sign() {
643+
for a in -10 .. 10 {
644+
for b in -10 .. 10 {
645+
if b == 0 {
646+
continue
647+
}
648+
big_a := big.integer_from_int(a)
649+
big_b := big.integer_from_int(b)
650+
assert (big_a % big_b).str() == (a % b).str()
651+
}
652+
}
653+
}
654+
642655
fn test_div_mod() {
643656
for t in div_mod_test_data {
644657
a := t.dividend.parse()

vlib/math/big/integer.v

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,10 @@ pub fn (dividend Integer) / (divisor Integer) Integer {
472472
// returns a Result refer to `mod_checked`.
473473
@[inline]
474474
pub fn (dividend Integer) % (divisor Integer) Integer {
475+
if dividend.signum == -1 {
476+
_, r := dividend.neg().div_mod(divisor)
477+
return r.neg()
478+
}
475479
_, r := dividend.div_mod(divisor)
476480
return r
477481
}

0 commit comments

Comments
 (0)