0

In my c code I have to perform a series of recursive modular operations. In particular I have to perform operations like (A*B)modC, with C~2^126, and A,B that, in principle, could be very big numbers (from 0 to 2^128 - 1) ( I work with 128 bit unsigned __int128 variables).
The problem is how to perform the module during the multiplication process. I need this because if the module is performed after the multiplication, I could exceed 2^128 (if A and B are very big) during the multiplication and corrupt the successive modular operation.
So I'd like to perform a multiplication which restart from 0 every time that I pass C (during the multiplication process) instead of every time I pass 2^128 - 1.
How should I do this?

user1172131
  • 103
  • 7

1 Answers1

1

The naive solution is to implement multiplication as a loop over bits, shifting by one and adding each time. This way you can compute the modulus of the interim result each pass through the loop.

It requires 128 shifts, 128 additions and 128 modulo operations. If that is too slow for you then some boffin can probably tell you an optimization (but everyone knows you should only consider optimization once you are sure that the simplest solution isn't fast enough).

Tom V
  • 4,827
  • 2
  • 5
  • 22
  • Thank you for your answer Tom V, I'm looking for a more direct way since I have to iterate the operation many times – user1172131 Feb 13 '21 at 19:37
  • The only other thing I can think of is you can translate (a * b) into (An + a) * (Bn + b), and choose n to be a power of 2, (2^64 if your machine can has 128 bit ints). This makes the multiplication much faster than working a bit at a time, but you then have to re-assemble the resulting 256 bit word and do 256 bit division. Sadly I don't think that there is an answer to this that is both simple and fast, apart from perhaps using an off-the-shelf bignum library where someone has done the work for you. – Tom V Feb 13 '21 at 19:51