. An analogous argument shows that one can compute all of the
s
i
also in time
O
(
L
(
a
)
L
(
b
)), and in fact, in time
O
(
L
(
b
)
2
).
2
We should point out that the Euclidean algorithm is not the fastest known algorithm for com
puting greatest common divisors. The asymptotically fastest known algorithm for computing the
greatest common divisor of two numbers of bit length at most
k
runs in time
O
(
k
(log
k
)
2
log log
k
).
One can also compute the corresponding values
s
and
t
within this time bound as well. Fast algo
rithms for greatest common divisors are not of much practical value, unless the integers involved
are
very
large — at least several tens of thousands of bits in length.
3.4
Computing in
Z
n
Let
n >
1. For computational purposes, we may represent elements of
Z
n
as elements of the set
{
0
, . . . , n

1
}
.
Addition and subtraction in
Z
n
can be performed in time
O
(
L
(
n
)).
Multiplication can be
performed in time
O
(
L
(
n
)
2
) with an ordinary integer multiplication, followed by a division with
remainder.
Given
a
∈ {
0
, . . . , n

1
}
, we can determine if [
a
mod
n
] has a multiplicative inverse in
Z
n
, and if
so, determine this inverse, in time
O
(
L
(
n
)
2
) by applying the extended Euclidean algorithm. More
precisely, we run the extended Euclidean algorithm to determine integers
d
,
s
, and
t
, such that
d
= gcd(
n, a
) and
ns
+
at
=
d
. If
d
6
= 1, then [
a
mod
n
] is not invertible; otherwise, [
a
mod
n
] is
invertible, and [
t
mod
n
] is its inverse. In the latter case, by part (vi) of Theorem 3.5, we know
that

t
 ≤
n
; we cannot have
t
=
±
n
, and so either
t
∈ {
0
, . . . , n

1
}
, or
t
+
n
∈ {
0
, . . . , n

1
}
.
Another interesting problem is exponentiation modulo
n
: given
a
∈ {
0
, . . . , n

1
}
and a non
negative integer
e
, compute
y
=
a
e
rem
n
.
Perhaps the most obvious way to do this is to it
eratively multiply by
a
modulo
n
,
e
times, requiring time
O
(
e
L
(
n
)
2
). A much faster algorithm,
the
repeatedsquaring algorithm
, computes
y
=
a
e
rem
n
using just
O
(
L
(
e
)) multiplications
modulo
n
, thus taking time
O
(
L
(
e
)
L
(
n
)
2
).
This method works as follows. Let
e
= (
b
‘

1
· · ·
b
0
)
2
be the binary expansion of
e
(where
b
0
is the
loworder bit). For 0
≤
i
≤
‘
, define
e
i
= (
b
‘

1
· · ·
b
i
)
2
. Also define, for 0
≤
i
≤
‘
,
y
i
=
a
e
i
rem
n
,
so
y
‘
= 1 and
y
0
=
y
. Then we have
e
i
= 2
e
i
+1
+
b
i
(0
≤
i < ‘
)
,
17