Square-and-Multiply Algorithm

Square-and-Multiply Algorithm is an algorithm used to compute exponentiation, especially for larger numbers, by repeatedly squaring base and multiplying in the ones that are needed to compute the result looking at binary representation of the exponent. The running time# of it is \(O(\lg n)\).

Let’s compute \(3^{23} \mod 7\) using this algorithm! First, we need to find out the base 2 version or binary representation of the exponent, \(23\), which is \(10111\). Reading the binary from left to right, we need to compute \(3^{1_2}\), \(3^{10_2}\), \(3^{101_2}\), \(3^{1011_2}\), and \(3^{10111_2}\) which are \(3^1\), \(3^2\), \(3^5\), \(3^{11}\), and \(3^{23}\) respectively. Utilising combination of multiplication and/or squaring, we can get the answer without computing a large exponent, but rather based our answer on previously computed result. The following shows the complete step for computing \(3^{23} \mod 7\):

$$ \begin{align*} 3^1 &= 3 \mod 7\\ &= 3\\ 3^2 &= 3^1 \cdot 3^1 \mod 7\\ &= 9 \mod 7\\ &= 2\\ 3^5 &= (3^2)^2 \cdot 3^1 \mod 7\\ &= 2^2 \cdot 3^1 \mod 7\\ &= 4 \cdot 3 \mod 7\\ &= 12 \mod 7\\ &= 5\\ 3^{11} &= (3^5)^2 \cdot 3^1 \mod 7\\ &= 5^2 \cdot 3^1 \mod 7\\ &= 25 \cdot 3 \mod 7\\ &= 75 \mod 7\\ &= 5\\ 3^{23} &= (3^{11})^2 \cdot 3^1 \mod 7\\ &= 5^2 \cdot 3^1 \mod 7\\ &= 5 \end{align*} $$

Thus, the computing result for \(3^{23} \mod 7\) is \(5\).

Links to this page
#math #algorithm