Suppose I have two long longs, a and b, which I need to multiply, then get the mod k value for some big k, so that a, b and k are all in the range of long long, but not inner. For simplicity, a, b <k.
Thus, the code will look like this:
long long a, b, k;
cin >> a >> b >> k;
cout << (a * b)%k << "\n";
However, since a and b are so large, if you multiply as above and it overflows and becomes negative, then mod k will be a negative number and incorrect.
How can you guarantee the correct mod k value?
Edit: as a bonus, how does it work in Java? Is this the same as expected? Or do you need BigInteger?
source
share