Skip to content

Commit

Permalink
[stdlib] Simplify Int.__floordiv__ and friends
Browse files Browse the repository at this point in the history
Signed-off-by: Yiwu Chen <[email protected]>
  • Loading branch information
soraros committed Oct 14, 2024
1 parent ebbe958 commit c7b4819
Showing 1 changed file with 12 additions and 29 deletions.
41 changes: 12 additions & 29 deletions stdlib/src/builtin/int.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -591,14 +591,11 @@ struct Int(
`floor(self/rhs)` value.
"""
# This should raise an exception
var denominator = select(rhs == 0, 1, rhs)
var div: Int = self._positive_div(denominator)

var mod = self - div * rhs
var div_mod = select(((rhs < 0) ^ (self < 0)) & mod, div - 1, div)
div = select(self > 0 & rhs > 0, div, div_mod)
div = select(rhs == 0, 0, div)
return div
denom = select(rhs == 0, 1, rhs)
div = self._positive_div(denom)
rem = self._positive_rem(denom)
res = select(((rhs < 0) ^ (self < 0)) & rem, div - 1, div)
return select(rhs == 0, 0, res)

@always_inline("nodebug")
fn __mod__(self, rhs: Int) -> Int:
Expand All @@ -610,16 +607,10 @@ struct Int(
Returns:
The remainder of dividing self by rhs.
"""
var denominator = select(rhs == 0, 1, rhs)
var div: Int = self._positive_div(denominator)

var mod = self - div * rhs
var div_mod = select(((rhs < 0) ^ (self < 0)) & mod, mod + rhs, mod)
mod = select(
self > 0 & rhs > 0, self._positive_rem(denominator), div_mod
)
mod = select(rhs == 0, 0, mod)
return mod
denom = select(rhs == 0, 1, rhs)
rem = self._positive_rem(denom)
res = select(((rhs < 0) ^ (self < 0)) & rem, rem + rhs, rem)
return select(rhs == 0, 0, res)

@always_inline("nodebug")
fn __divmod__(self, rhs: Int) -> Tuple[Int, Int]:
Expand All @@ -629,17 +620,9 @@ struct Int(
rhs: The value to divide on.
Returns:
The quotient and remainder as a `Tuple(self // rhs, self % rhs)`.
"""
if rhs == 0:
return 0, 0
var div: Int = self._positive_div(rhs)
if rhs > 0 & self > 0:
return div, self._positive_rem(rhs)
var mod = self - div * rhs
if ((rhs < 0) ^ (self < 0)) & mod:
return div - 1, mod + rhs
return div, mod
The quotient and remainder as a tuple `(self // rhs, self % rhs)`.
"""
return self // rhs, self % rhs

@always_inline("nodebug")
fn __pow__(self, exp: Self) -> Self:
Expand Down

0 comments on commit c7b4819

Please sign in to comment.