Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 26 additions & 10 deletions include/real/exact_number.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,20 @@ namespace boost {
this->normalize();
}

// returns (a+b)%mod
T addn(T a, T b, T mod){
T min = std::min(a, b);
T max = std::max(a, b);
if(max<(mod-min)){
return (max+min);
}
if(mod%2==0){
return (max-mod/2)-(mod/2-min);
}else{
return (max-mod/2)-(mod/2-min)-1;
}
}

//Returns (a*b)%mod
T mulmod(T a, T b, T mod)
{
Expand All @@ -154,10 +168,10 @@ namespace boost {
{
// If b is odd, add 'a' to result
if (b % 2 == 1)
res = (res + a) % mod;
res = addn(res, a, mod);

// Multiply 'a' with 2
a = (a * 2) % mod;
a = addn(a, a, mod);

// Divide b by 2
b /= 2;
Expand All @@ -175,17 +189,19 @@ namespace boost {
// a < c, rem < c.
while (b != 0) {
if (b & 1) {
rem += a;
if (rem >= c) {
rem -= c;
res++;
if(rem >= (c-a)){
rem = addn(rem, a, c);
res++;
}else{
rem = rem + a;
}
}
b /= 2;
a *= 2;
if (a >= c) {
a -= c;
res += b;
if(a >= (c-a)){
a = addn(a, a, c);
res += b;
}else{
a *= 2;
}
}
return res;
Expand Down
48 changes: 48 additions & 0 deletions test/real_overflow_multiplication_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#include <catch2/catch.hpp>
// #include <map>

#include <real/real.hpp>
#include <test_helpers.hpp>

TEST_CASE("Overflow in Multiplication check") {
SECTION("A"){
boost::real::real <int> a1("2123643646");
boost::real::real <int> b1("2147471816");
boost::real::real <int> c1;
boost::real::real <int> d1("4560464877012481136");
c1 = a1*b1;
CHECK(d1 == c1);
}
SECTION("B"){
boost::real::real <int> a2("2320102120234");
boost::real::real <int> b2("1201320452302");
boost::real::real <int> c2;
boost::real::real <int> d2("2787186128466338066078668");
c2 = a2*b2;
CHECK(d2 == c2);
}
SECTION("C"){
boost::real::real <int> a3("4524435689");
boost::real::real <int> b3("6870530492");
boost::real::real <int> c3;
boost::real::real <int> d3("31085273360367528988");
c3 = a3*b3;
CHECK(d3 == c3);
}
SECTION("D"){
boost::real::real <int> a4("7869349424036");
boost::real::real <int> b4("3435469507547");
boost::real::real <int> c4;
boost::real::real <int> d4("27034909990508225005199692");
c4 = a4*b4;
CHECK(d4 == c4);
}
SECTION("E"){
boost::real::real <int> a5("2123453646");
boost::real::real <int> b5("2147482316");
boost::real::real <int> c5;
boost::real::real <int> d5("4560079153630724136");
c5 = a5*b5;
CHECK(d5 == c5);
}
}