How does int(or long long) overflow in c++ affect modulus? -
suppose have 2 long longs, , b, need multiply, value mod k large k, such a, b, , k in range of long long not of int. simplicity, a, b < k.
thus code be:
long long a, b, k; cin >> >> b >> k; cout << (a * b)%k << "\n";
however, since , b large, if multiply above, , overflows , becomes negative, mod k negative number , incorrect.
how can ensure value mod k correct?
edit: bonus, how work in java? same, expected? or biginteger needed?
many compilers offer 128-bit integral type. example, g++
can make function
static inline int64_t mulmod(int64_t x, int64_t y, int64_t m) { return ( (__int128_t)x * y) % m; }
aside: if can, try stick unsigned integer types when you're doing modular arithmetic. rounding behavior of integer division makes using %
awkward when signed values involved.
Comments
Post a Comment