Montgomery multiplication is a faster way to do multiplication which prefers base 2 to base 10, and shines when used iteratively. Numbers are “represented” in montgomery form during the primary operations, and then once those operations are complete, they are transported back to their original form. It solves a modular multiplication of the form:

\[ a * b\ \text{mod}\ m \]

We will use \(a\), \(b\) and \(m\) in our example below.

First we compute or choose a few constants. These can be precomputed and then retained, they don’t need to be regenerated each time.

Choose a power of two that’s greater than \(m\), this is \(r\). Below I’m computing a number, but this could just as easily be chosen to be constant \(2^{64}\) or something like that.

`= 2 ^ ceiling (logBase 2 (fromIntegral m)) r`

Square \(r\), modulo \(m\). This we’ll call \(r_2\).

`= r * r `mod` m r2`

Compute the multiplicative inverse of \(-m\ \text{mod}\ r\), this is \(m'\)

`= inv (negate m) r m'`

Now we’ll use these to compute the montgomery form of our input variables.

Multiply \(a * r_2\), this is \(a_m\).

`= a * r2 am`

Multiply \(a_m\) by \(m'\ \text{mod}\ r\), I’ll call this \(a_m'\)

`= am * m' `mod` r am'`

Next we do a reduction of the montgomery form.

Do \(\cfrac{a_m + a_m' * m}{r}\). This temp value we’ll call \(t\).

`= am + am' * m `div` r t`

The result montgomery form is \(t\) if \(t < m\), otherwise it’s \(t - m\).

`if t < m then t else t - m`

We do the same for \(b\), then