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;
Asked
Active
Viewed 221 times
3

Peter O.
- 32,158
- 14
- 82
- 96

sumit kumar Pradhan
- 145
- 1
- 8
-
@Ron both `a*b` and `c*d` can overflow – fas Jan 13 '21 at 07:59
-
4Does this answer your question? [How to avoid overflow in expr. A \* B - C \* D](https://stackoverflow.com/questions/13237046/how-to-avoid-overflow-in-expr-a-b-c-d) – jhcarl0814 Jan 13 '21 at 08:02
-
@jhcarl0814 appreciate for the ans. – sumit kumar Pradhan Jan 13 '21 at 08:13
2 Answers
2
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.

Laurent Jospin
- 604
- 5
- 9
-
Very nice suggestion (already upvoted). You may want to elaborate on whether special care is needed for positive and negative and 0 cases. – jxh Jan 13 '21 at 21:48
-
Yes, I assumed all numbers are strictly positive. Actually, comparing a - d and c - b should should do the trick too, and works to negative numbers and zero. Depending on the order of magnitudes, comparing (a - d) + b and c or a and (c - b) + d might be an option too. – Laurent Jospin Jan 14 '21 at 23:27
0
#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);
}

jhcarl0814
- 108
- 2
- 8