How to compare product of two variables in c++ without directly multiplying them(due to overflow)?

Viewed 165

how to compute that a*b > c*d and store a value for later comparison with any other two pairs. The product is overflowed during multiplication in c++. long long a = 12345678912, b=45697845821, c=47896512354, d=741258963256;

2 Answers

You can cast to float and compare a/d and c/b. Alternatively you can stay with ints and if a/d == c/b then you compare a%d and c%b.

#include<boost/multiprecision/integer.hpp>
void f()
{
    long long int a_ = 12345678912;
    long long int b_ = 45697845821;
    boost::multiprecision::int128_t a(a_);
    boost::multiprecision::int128_t b(b_);
    boost::multiprecision::int128_t ab(a * b); // store a value for later comparison with any other two pairs
    bool greater_than = ab > boost::multiprecision::int128_t(47896512354) * boost::multiprecision::int128_t(741258963256);
}
Related