Residue Number System

To write "real" cryptography, you've gotta be aware of RNS. A naive implementation of cryptographic schemes, which all rely on modular arithmetic on rather large numbers (and typically with moduli other than native powers of 2), is going to be ridiculously slow without such optimizations.

Thanks to the Chinese Remainder Theorem, given any relatively prime moduli p1,,pnp_1,\ldots,p_n, for all x0,,P1x \in {0, \ldots, P-1} where P=piP = \prod p_i, there exists a unique representation x=[xi]x = [x_i] where xi=xmod  pix_i = x \mod p_i. The xix_i are called the residues of xx.

We can make a signed RNS by designating X<P/2X < P/2 as positive and XP/2X \ge P/2 as negative. The complement XCX^C of XX is PXmod  PP - X \mod P. Then subtraction is simply XY=X+YCX - Y = X + Y^C.