Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate modulus of the form (a*b)%c?

How to calculate modulus of the form (a*b)%c?

i want to calculate modulus of multiplication of two int numbers where they are almost in the stage of overflow...

here c is also int

like image 301
Kunal Avatar asked May 06 '11 18:05

Kunal


3 Answers

(a * b) % c == ((a % c) * (b % c)) % c
like image 107
kennytm Avatar answered Oct 03 '22 07:10

kennytm


What about ((a % c) * (b % c)) % c? Depending on your architecture this could be faster or slower than casting to a bigger type.

like image 27
Mark B Avatar answered Oct 03 '22 08:10

Mark B


You may cast a and c to long long, so the multiplication won't overflow.

((long long)a * (long long)b) % c
like image 39
buc Avatar answered Oct 03 '22 09:10

buc