How can I calculate (A*B)%C for A,B,C <= 10^18, in C++?
问题 For example, A=10^17, B=10^17, C=10^18. The product A*B exceeds the limit of long long int. Also, writing ((A%C)*(B%C))%C doesn't help. 回答1: Assuming you want to stay within 64-bit integer operations, you can use binary long division, which boils down to a bunch of adds and multiply by two operations. This means you also need overflow-proof versions of those operators, but those are relatively simple. Here is some Java code that assumes A and B are already positive and less than M. If not, it