Skip to content

Commit

Permalink
Fix division bug discovered by https://svn.boost.org/trac/boost/ticke…
Browse files Browse the repository at this point in the history
  • Loading branch information
jzmaddock committed Sep 22, 2015
1 parent a752269 commit a1eafc4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
16 changes: 15 additions & 1 deletion include/boost/multiprecision/cpp_int/divide.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,21 @@ void divide_unsigned_helper(
// Update r in a way that won't actually produce a negative result
// in case the argument types are unsigned:
//
if(r.compare(t) > 0)
if(truncated_t && carry)
{
// We need to calculate 2^n + t - r
// where n is the number of bits in this type.
// Simplest way is to get 2^n - r by complementing
// r, then add t to it. Note that we can't call eval_complement
// in case this is a signed checked type:
for(unsigned i = 0; i <= r_order; ++i)
r.limbs()[i] = ~prem[i];
r.normalize();
eval_increment(r);
eval_add(r, t);
r_neg = !r_neg;
}
else if(r.compare(t) > 0)
{
eval_subtract(r, t);
}
Expand Down
10 changes: 10 additions & 0 deletions test/test_cpp_int.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,16 @@ struct tester
c = a ^ b;
test_type d = ~(a ^ ~b);
BOOST_CHECK_EQUAL(c, d);
#endif
#if defined(TEST2) || defined(TEST3)
// https://svn.boost.org/trac/boost/ticket/11648
a = (std::numeric_limits<test_type>::max)() - 69;
b = a / 139;
++b;
c = a / b;
test_type r = a % b;
BOOST_CHECK(r < b);
BOOST_CHECK_EQUAL(a - c * b, r);
#endif
}

Expand Down

0 comments on commit a1eafc4

Please sign in to comment.