The Tonelli–Shanks algorithm (referred to by Shanks as the RESSOL algorithm) is used within modular arithmetic to solve a congruence of the form
Contents
where n is a quadratic residue (mod p), and p is an odd prime.
Tonelli–Shanks cannot be used for composite moduli; finding square roots modulo composite numbers is a computational problem equivalent to integer factorization.
An equivalent, but slightly more redundant version of this algorithm was developed by Alberto Tonelli in 1891. The version discussed here was developed independently by Daniel Shanks in 1973, who explained:
"My tardiness in learning of these historical references was because I had lent Volume 1 of Dickson's History to a friend and it was never returned."
The algorithm
(Note: All
Inputs: p, an odd prime. n, an integer which is a quadratic residue (mod p), meaning that the Legendre symbol
Outputs: R, an integer satisfying
- Factor out powers of 2 from p − 1, defining Q and S as:
p − 1 = Q 2 S S = 1 , i.e.p ≡ 3 ( mod 4 ) , then solutions are given directly byR ≡ ± n p + 1 4 - Select a z such that the Legendre symbol
( z p ) = − 1 (that is, z is a quadratic non-residue modulo p), and setc ≡ z Q - Let
R ≡ n Q + 1 2 , t ≡ n Q , M = S . - Loop:
- If
t ≡ 1 , return R. - Otherwise, find the lowest i,
0 < i < M , such thatt 2 i ≡ 1 ; e.g. via repeated squaring. - Let
b ≡ c 2 ( M − i − 1 ) R ≡ R b , t ≡ t b 2 , c ≡ b 2 M = i .
- If
Once you have solved the congruence with R the second solution is p − R.
Example
Solving the congruence
Indeed, observe that
Proof
First write
If
Similarly we have
Now we set
If
Speed of the algorithm
The Tonelli–Shanks algorithm requires (on average over all possible input (quadratic residues and quadratic nonresidues))
modular multiplications, where
This shows essentially that the Tonelli–Shanks algorithm works very well if the modulus
The algorithm requires us to find a quadratic nonresidue
Uses
The Tonelli–Shanks algorithm can (naturally) be used for any process in which square roots modulo a prime are necessary. For example, it can be used for finding points on elliptic curves. It is also useful for the computations in the Rabin cryptosystem.
Generalizations
Tonelli–Shanks can be generalized to any cyclic group (instead of
If many square-roots must be done in the same cyclic group and S is not too large, a table of square-roots of the elements of 2-power order can be prepared in advance and the algorithm simplified and sped up as follows.
- Factor out powers of 2 from p − 1, defining Q and S as:
p − 1 = Q 2 S - Let
R ≡ n Q + 1 2 , t ≡ n Q ≡ R 2 / n - Find
b from the table such thatb 2 ≡ t and setR ≡ R / b - return R.