Skip to content

Commit

Permalink
math.big: fix incorrect division with negative numbers (fix #19585) (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
shove70 authored Oct 17, 2023
1 parent dc6e317 commit 69d62e4
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
18 changes: 18 additions & 0 deletions vlib/math/big/big_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,21 @@ const div_mod_test_data = [
]
// vfmt on

struct DivTest {
dividend TestInteger
divisor TestInteger
quotient TestInteger
}

// vfmt off
const div_test_data = [
DivTest{1234, 10, 123},
DivTest{-1234, 10, -123},
DivTest{1234, -10, -123},
DivTest{-1234, -10, 123},
]
// vfmt on

enum Comparison {
less = -1
equal = 0
Expand Down Expand Up @@ -554,6 +569,9 @@ fn test_div() {
for t in div_mod_test_data {
assert t.dividend.parse() / t.divisor.parse() == t.quotient.parse()
}
for t in div_test_data {
assert t.dividend.parse() / t.divisor.parse() == t.quotient.parse()
}
}

fn test_mod() {
Expand Down
4 changes: 4 additions & 0 deletions vlib/math/big/integer.v
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,10 @@ pub fn (dividend Integer) div_mod_checked(divisor Integer) !(Integer, Integer) {
// refer to `div_checked`.
[inline]
pub fn (dividend Integer) / (divisor Integer) Integer {
if dividend.signum == -1 {
q, _ := dividend.neg().div_mod(divisor)
return q.neg()
}
q, _ := dividend.div_mod(divisor)
return q
}
Expand Down

0 comments on commit 69d62e4

Please sign in to comment.