Skip to content

Commit 65767d2

Browse files
authored
math.big: fix the + operator for big.Integer for negative numbers, add test (#24487)
1 parent 2ca9209 commit 65767d2

File tree

2 files changed

+16
-12
lines changed

2 files changed

+16
-12
lines changed

vlib/math/big/big_test.v

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -598,6 +598,16 @@ fn test_addition() {
598598
}
599599
}
600600

601+
fn test_add_sign() {
602+
for a in -10 .. 10 {
603+
for b in -10 .. 10 {
604+
big_a := big.integer_from_int(a)
605+
big_b := big.integer_from_int(b)
606+
assert (big_a + big_b).str() == (a + b).str()
607+
}
608+
}
609+
}
610+
601611
fn test_subtraction() {
602612
for t in sub_test_data {
603613
assert t.minuend.parse() - t.subtrahend.parse() == t.difference.parse(), 't.minuend: ${t.minuend} - t.subtrahend: ${t.subtrahend}'

vlib/math/big/integer.v

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -316,18 +316,12 @@ pub fn (augend Integer) + (addend Integer) Integer {
316316
if augend.signum == addend.signum {
317317
return augend.add(addend)
318318
}
319-
// Unequal signs, left is negative:
320-
if augend.signum == -1 {
321-
// -1 + 5 == 5 - 1
322-
return addend.subtract(augend)
323-
}
324-
// Unequal signs, left is positive:
325-
res := augend.subtract(addend)
326-
cmp := augend.abs_cmp(addend)
327-
if cmp < 0 {
328-
return res.neg()
329-
}
330-
return res
319+
// Unequal signs
320+
if augend.abs_cmp(addend) < 0 {
321+
return augend.subtract(addend).neg()
322+
} else {
323+
return augend.subtract(addend)
324+
}
331325
}
332326

333327
// - returns the difference of the integers `minuend` and `subtrahend`

0 commit comments

Comments
 (0)