I have 3 large 64 bit numbers: A, B and C. I want to compute:
(A x B) mod C
considering my registers are 64 bits, i.e. writing a * b
actually yields (A x B) mod 2⁶⁴.
What is the best way to do it? I am coding in C, but don't think the language is relevant in this case.
After getting upvotes on the comment pointing to this solution:
(a * b) % c == ((a % c) * (b % c)) % c
let me be specific: this isn't a solution, because ((a % c) * (b % c)) may still be bigger than 2⁶⁴, and the register would still overflow and give me the wrong answer. I would have:
(((A mod C) x (B mod C)) mod 2⁶⁴) mod C
(A*B)%C
it works ... or not ? – IniquityA*B
overflows in C (N-bit number multiplied by N-bit number should ideally give you 2N-bit number, but that's not how arithmetic works in C), so you can't just use this truncated product. – GreathouseC
tag , I BeliveC
people can help you better – Iniquity(A*B) mod C == ((A mod C) * (B mod C)) mod C
make it easier? – Inefficiency(a * b) % c == ((a % c) * (b % c)) % c
doesn't help at all:((a % c) * (b % c))
may still overflow the 64 bit register. – Mantineamov rax, rdx
beforeret
. – Greathouse