length. For example, we could encode inputs in some base other than 2 (but not unary!) or use a
different alphabet. However, such an alternative encoding scheme would change the definition of
input length by at most a constant multiplicative factor, and so would not affect the notion of a
polynomialtime algorithm.
We stress that algorithms may use data structures for representing mathematical objects that
look quite different from whatever encoding scheme one might choose.
3.2
Basic Integer Arithmetic
We will need algorithms to manipulate integers of arbitrary length. Since such integers will exceed
the wordsize of actual machines, we represent large integers as vectors of digits to some base
B
,
along with a bit indicating the sign. Thus, for
x
∈
Z
, we write
x
=
±
(
k

1
X
i
=0
x
i
B
i
) =
±
(
x
k

1
· · ·
x
1
x
0
)
B
,
where 0
≤
x
i
< B
for 0
≤
i < k
, and usually, we shall have
x
k

1
6
= 0.
The integer
x
will be
represented in memory as a data structure consisting of a vector of digits and a signbit. For our
purposes, we shall consider
B
to be a constant, and moreover, a power of 2. The choice of
B
as a
power of 2 allows us to extract an arbitrary bit in the binary representation of a number in time
O
(1).
We discuss basic arithmetic algorithms for positive integers; they can be very easily adapted to
deal with signed integers. All of these algorithms can be implemented directly in a programming
language that provides a “builtin” signed integer type that can represent all integers whose absolute
value is less than
B
2
, and that provides the basic arithmetic operations (addition, subtraction,
multiplication, integer division). So, for example, using the
C
programming language’s
int
type on
a typical 32bit computer, we could take
B
= 2
15
. The resulting algorithms would be reasonably
efficient, but not nearly as efficient as algorithms that are much more carefully implemented, and
which take advantage of lowlevel “assembly language” codes specific to a particular machine’s
architecture (e.g., the GNU MultiPrecision library GMP, available as
http://www.swox.com/gmp
).
Suppose we have two positive integers
a
and
b
, represented with
k
and
‘
base
B
digits, re
spectively, with
k
≥
‘
.
So we have
a
= (
a
k

1
· · ·
a
0
)
B
and
b
= (
b
‘

1
· · ·
b
0
)
B
.
Then using the
standard “paperandpencil” method (adapted from base10 to base
B
, of course), we can compute
the base
B
representation of
a
+
b
or
a

b
in time
O
(
k
).
Using the standard paperandpencil technique, we can compute the
k
+ 1 digit product
a
·
b
0
in time
O
(
k
). We can then compute the
k
+
‘
digit product
c
=
a
·
b
as follows:
c
←
0
for
i
←
0 to
‘

1 do
c
←
c
+
B
i
·
ab
i
As each loopiteration of this algorithm takes time
O
(
k
), the total runningtime is
O
(
k‘
).