Skip to content

Commit ef21783

Browse files
committed
Optimize signed integer multiplication
1 parent c9caa8b commit ef21783

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

include/slimcpplib/long_int.h

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ class long_int_t : public long_uint_t<native_t, size>
8080
constexpr long_int_t& operator=(long_int_t&& that) noexcept = default;
8181

8282
constexpr bool sign() const noexcept;
83+
constexpr long_int_t& negate() noexcept;
8384
template<uint_t other_size, std::enable_if_t<(other_size < size), int> = 0>
8485
explicit constexpr operator long_int_t<native_t, other_size>() const noexcept;
8586
template<typename type_t, std::enable_if_t<std::is_signed_v<type_t>, int> = 0>
@@ -212,6 +213,21 @@ constexpr bool long_int_t<native_t, size>::sign() const noexcept
212213

213214

214215

216+
////////////////////////////////////////////////////////////////////////////////////////////////////
217+
template<typename native_t, uint_t size>
218+
constexpr long_int_t<native_t, size>& long_int_t<native_t, size>::negate() noexcept
219+
{
220+
bool borrow = true;
221+
222+
for (uint_t n = 0; n < std::size(digits); ++n)
223+
digits[n] = ~subb<native_t>(digits[n], 0, borrow);
224+
225+
return *this;
226+
}
227+
228+
229+
230+
215231
////////////////////////////////////////////////////////////////////////////////////////////////////
216232
template<typename native_t, uint_t size>
217233
template<uint_t other_size, std::enable_if_t<(other_size < size), int>>
@@ -379,15 +395,10 @@ constexpr long_int_t<native_t, size> long_int_t<native_t, size>::operator-() con
379395
template<typename native_t, uint_t size>
380396
constexpr long_int_t<native_t, size>& long_int_t<native_t, size>::operator*=(const long_int_t& that) noexcept
381397
{
382-
const long_uint_t<native_t, size> value1 = this->sign() ? -*this : *this;
383-
const long_uint_t<native_t, size> value2 = that.sign() ? -that : that;
384-
385-
long_uint_t<native_t, size> result = value1 * value2;
398+
long_uint_t<native_t, size>::operator*=(that.sign() ? -that : that);
386399

387-
if (this->sign() ^ that.sign())
388-
result = -result;
389-
390-
*this = result;
400+
if (that.sign())
401+
negate();
391402

392403
return *this;
393404
}

0 commit comments

Comments
 (0)