Skip to content

Commit

Permalink
std::math::big: minor refactoring and fix for subtraction computation
Browse files Browse the repository at this point in the history
  • Loading branch information
mertcandav committed Sep 7, 2024
1 parent ff4d7fd commit b477374
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 20 deletions.
30 changes: 12 additions & 18 deletions std/math/big/int.jule
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,11 @@ impl Int {
// (-x) + y == y - x == -(x - y)
if self.nat.cmp(y.nat) >= 0 {
self.nat -= y.nat
self.minus = self.minus && self.nat.len() > 0 // 0 has no sign
} else {
self.minus = !self.minus
self.nat = y.nat - self.nat
self.minus = !self.minus && self.nat.len() > 0 // 0 has no sign
}
self.minus = self.minus && self.nat.len() > 0 // 0 has no sign
}
}

Expand All @@ -107,27 +107,21 @@ impl Int {

// Subtracts Int.
fn SubAssign(mut self, y: Int) {
if y.Len() == 0 {
ret
}
mut cmp := self.Cmp(y)
if cmp == 0 {
self.minus = false
self.nat = nat.zero()
ret
}
if self.minus == y.minus {
self.minus = cmp == -1
if cmp == +1 {
if self.minus != y.minus {
// x - (-y) == x + y
// (-x) - y == -(x + y)
self.nat += y.nat
} else {
// x - y == x - y == -(y - x)
// (-x) - (-y) == y - x == -(x - y)
if self.nat.cmp(y.nat) >= 0 {
self.nat -= y.nat
} else {
self.minus = !self.minus
self.nat = y.nat - self.nat
}
ret
self.minus = self.minus && self.nat.len() > 0 // 0 has no sign
}
self.minus = false
self.nat += y.nat
ret
}

// Multiplies two Int and returns result.
Expand Down
4 changes: 2 additions & 2 deletions std/math/big/int_test.jule
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ static casesIntSub = [
["+10000100100001", "+10011001101010", "-10101001001"],
["+10000100100001", "-10011001101010", "+100011110001011"],
["+10011001101010", "-10000100100001", "+100011110001011"],
["-10011001101010", "+10000100100001", "+100011110001011"],
["-10000100100001", "+10011001101010", "+100011110001011"],
["-10011001101010", "+10000100100001", "-100011110001011"],
["-10000100100001", "+10011001101010", "-100011110001011"],
["-100011", "-1110100110", "+1110000011"],
["+11000", "+101011", "-10011"],
]
Expand Down

0 comments on commit b477374

Please sign in to comment.