

























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


























One of the main themes of this chapter is the dramatic contrast between two ancient problems that at first seem very similar:
Factoring: Given a number N , express it as a product of its prime factors. Primality: Given a number N , determine whether it is a prime.
Factoring is hard. Despite centuries of effort by some of the world’s smartest mathemati- cians and computer scientists, the fastest methods for factoring a number N take time expo- nential in the number of bits of N. On the other hand, we shall soon see that we can efficiently test whether N is prime! And (it gets even more interesting) this strange disparity between the two intimately related problems, one very hard and the other very easy, lies at the heart of the technology that enables secure communication in today’s global information environment. En route to these insights, we need to develop algorithms for a variety of computational tasks involving numbers. We begin with basic arithmetic, an especially appropriate starting point because, as we know, the word algorithms originally applied only to methods for these problems.
We were so young when we learned the standard technique for addition that we would scarcely have thought to ask why it works. But let’s go back now and take a closer look. It is a basic property of decimal numbers that
The sum of any three single-digit numbers is at most two digits long.
Quick check: the sum is at most 9 + 9 + 9 = 27, two digits long. In fact, this rule holds not just in decimal but in any base b ≥ 2 (Exercise 1.1). In binary, for instance, the maximum possible sum of three single-bit numbers is 3, which is a 2-bit number.
21
22 Algorithms
Naturally, there is nothing special about the number 10—we just happen to have 10 fingers, and so 10 was an obvious place to pause and take counting to the next level. The Mayans developed a similar positional system based on the number 20 (no shoes, see?). And of course today computers represent numbers in binary. How many digits are needed to represent the number N ≥ 0 in base b? Let’s see—with k digits in base b we can express numbers up to bk^ − 1 ; for instance, in decimal, three digits get us all the way up to 999 = 10^3 − 1. By solving for k, we find that dlogb(N + 1)e digits (about logb N digits, give or take 1) are needed to write N in base b. How much does the size of a number change when we change bases? Recall the rule for converting logarithms from base a to base b: logb N = (loga N )/(loga b). So the size of integer N in base a is the same as its size in base b, times a constant factor loga b. In big-O notation, therefore, the base is irrelevant, and we write the size simply as O(log N ). When we do not specify a base, as we almost never will, we mean log 2 N.
Incidentally, this function log N appears repeatedly in our subject, in many guises. Here’s a sampling:
This simple rule gives us a way to add two numbers in any base: align their right-hand ends, and then perform a single right-to-left pass in which the sum is computed digit by digit, maintaining the overflow as a carry. Since we know each individual sum is a two-digit number, the carry is always a single digit , and so at any given step, three single-digit numbers are added. Here’s an example showing the addition 53 + 35 in binary.
Carry: 1 1 1 1 1 1 0 1 0 1 (53) 1 0 0 0 1 1 (35) 1 0 1 1 0 0 0 (88)
Ordinarily we would spell out the algorithm in pseudocode, but in this case it is so familiar that we do not repeat it. Instead we move straight to analyzing its efficiency. Given two binary numbers x and y , how long does our algorithm take to add them? This
24 Algorithms
1 1 0 1 (1101 times 1) 1 1 0 1 (1101 times 1, shifted once) 0 0 0 0 (1101 times 0, shifted twice)
1 0 0 0 1 1 1 1 (binary 143)
In binary this is particularly easy since each intermediate row is either zero or x itself, left- shifted an appropriate amount of times. Also notice that left-shifting is just a quick way to multiply by the base, which in this case is 2. (Likewise, the effect of a right shift is to divide by the base, rounding down if needed.) The correctness of this multiplication procedure is the subject of Exercise 1.6; let’s move on and figure out how long it takes. If x and y are both n bits, then there are n intermediate rows, with lengths of up to 2 n bits (taking the shifting into account). The total time taken to add up these rows, doing two numbers at a time, is
O(n) + O(n) + · · · + O(n) ︸ ︷︷ ︸ n − 1 times
which is O(n^2 ), quadratic in the size of the inputs: still polynomial but much slower than addition (as we have all suspected since elementary school). But Al Khwarizmi knew another way to multiply, a method which is used today in some European countries. To multiply two decimal numbers x and y, write them next to each other, as in the example below. Then repeat the following: divide the first number by 2 , rounding down the result (that is, dropping the. 5 if the number was odd), and double the second number. Keep going till the first number gets down to 1. Then strike out all the rows in which the first number is even, and add up whatever remains in the second column.
11 13 5 26 2 52 (strike out) 1 104
143 (answer)
But if we now compare the two algorithms, binary multiplication and multiplication by re- peated halvings of the multiplier, we notice that they are doing the same thing! The three numbers added in the second algorithm are precisely the multiples of 13 by powers of 2 that were added in the binary method. Only this time 11 was not given to us explicitly in binary, and so we had to extract its binary representation by looking at the parity of the numbers ob- tained from it by successive divisions by 2. Al Khwarizmi’s second algorithm is a fascinating mixture of decimal and binary!
S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 25
Figure 1.1 Multiplication `a la Franc¸ais.
function multiply(x, y) Input: Two n-bit integers x and y, where y ≥ 0 Output: Their product
if y = 0: return 0 z = multiply(x, by/ 2 c) if y is even: return 2 z else: return x + 2z
The same algorithm can thus be repackaged in different ways. For variety we adopt a third formulation, the recursive algorithm of Figure 1.1, which directly implements the rule
x · y =
2(x · by/ 2 c) if y is even x + 2(x · by/ 2 c) if y is odd.
Is this algorithm correct? The preceding recursive rule is transparently correct; so check- ing the correctness of the algorithm is merely a matter of verifying that it mimics the rule and that it handles the base case (y = 0) properly. How long does the algorithm take? It must terminate after n recursive calls, because at each call y is halved—that is, its number of bits is decreased by one. And each recursive call requires these operations: a division by 2 (right shift); a test for odd/even (looking up the last bit); a multiplication by 2 (left shift); and possibly one addition, a total of O(n) bit operations. The total time taken is thus O(n^2 ), just as before. Can we do better? Intuitively, it seems that multiplication requires adding about n multi- ples of one of the inputs, and we know that each addition is linear, so it would appear that n^2 bit operations are inevitable. Astonishingly, in Chapter 2 we’ll see that we can do significantly better!
Division is next. To divide an integer x by another integer y 6 = 0 means to find a quotient q and a remainder r, where x = yq + r and r < y. We show the recursive version of division in Figure 1.2; like multiplication, it takes quadratic time. The analysis of this algorithm is the subject of Exercise 1.8.
With repeated addition or multiplication, numbers can get cumbersomely large. So it is for- tunate that we reset the hour to zero whenever it reaches 24 , and the month to January after every stretch of 12 months. Similarly, for the built-in arithmetic operations of computer pro-
S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 27
N − 1. For example, there are three equivalence classes modulo 3 :
· · · − 9 − 6 − 3 0 3 6 9 · · · · · · − 8 − 5 − 2 1 4 7 10 · · · · · · − 7 − 4 − 1 2 5 8 11 · · ·
Any member of an equivalence class is substitutable for any other; when viewed modulo 3 , the numbers 5 and 11 are no different. Under such substitutions, addition and multiplication remain well-defined:
Substitution rule If x ≡ x′^ (mod N ) and y ≡ y′^ (mod N ) , then:
x + y ≡ x′^ + y′^ (mod N ) and xy ≡ x′y′^ (mod N ).
(See Exercise 1.9.) For instance, suppose you watch an entire season of your favorite television show in one sitting, starting at midnight. There are 25 episodes, each lasting 3 hours. At what time of day are you done? Answer: the hour of completion is (25 × 3) mod 24, which (since 25 ≡ 1 mod 24) is 1 × 3 = 3 mod 24, or three o’clock in the morning. It is not hard to check that in modular arithmetic, the usual associative, commutative, and distributive properties of addition and multiplication continue to apply, for instance:
x + (y + z) ≡ (x + y) + z (mod N ) Associativity xy ≡ yx (mod N ) Commutativity x(y + z) ≡ xy + yz (mod N ) Distributivity
Taken together with the substitution rule, this implies that while performing a sequence of arithmetic operations, it is legal to reduce intermediate results to their remainders modulo N at any stage. Such simplifications can be a dramatic help in big calculations. Witness, for instance: 2345 ≡ (2^5 )^69 ≡ 3269 ≡ 169 ≡ 1 (mod 31).
To add two numbers x and y modulo N , we start with regular addition. Since x and y are each in the range 0 to N − 1 , their sum is between 0 and 2(N − 1). If the sum exceeds N − 1 , we merely need to subtract off N to bring it back into the required range. The overall computation therefore consists of an addition, and possibly a subtraction, of numbers that never exceed 2 N. Its running time is linear in the sizes of these numbers, in other words O(n), where n = dlog N e is the size of N ; as a reminder, our convention is to use the letter n to denote input size. To multiply two mod-N numbers x and y, we again just start with regular multiplication and then reduce the answer modulo N. The product can be as large as (N −1)^2 , but this is still at most 2 n bits long since log(N − 1)^2 = 2 log(N − 1) ≤ 2 n. To reduce the answer modulo N , we
28 Algorithms
Modular arithmetic is nicely illustrated in two’s complement , the most common format for storing signed integers. It uses n bits to represent numbers in the range [− 2 n−^1 , 2 n−^1 − 1] and is usually described as follows:
(And the usual description of addition and multiplication in this format is even more arcane!)
Here’s a much simpler way to think about it: any number in the range − 2 n−^1 to 2 n−^1 − 1 is stored modulo 2 n. Negative numbers −x therefore end up as 2 n^ − x. Arithmetic operations like addition and subtraction can be performed directly in this format, ignoring any overflow bits that arise.
compute the remainder upon dividing it by N , using our quadratic-time division algorithm. Multiplication thus remains a quadratic operation. Division is not quite so easy. In ordinary arithmetic there is just one tricky case—division by zero. It turns out that in modular arithmetic there are potentially other such cases as well, which we will characterize toward the end of this section. Whenever division is legal, however, it can be managed in cubic time, O(n^3 ).
To complete the suite of modular arithmetic primitives we need for cryptography, we next turn to modular exponentiation , and then to the greatest common divisor , which is the key to division. For both tasks, the most obvious procedures take exponentially long, but with some ingenuity polynomial-time solutions can be found. A careful choice of algorithm makes all the difference.
In the cryptosystem we are working toward, it is necessary to compute xy^ mod N for values of x, y, and N that are several hundred bits long. Can this be done quickly? The result is some number modulo N and is therefore itself a few hundred bits long. How- ever, the raw value of xy^ could be much, much longer than this. Even when x and y are just
20 -bit numbers, xy^ is at least (2^19 )(
(^19) ) = 2(19)(524288)^ , about 10 million bits long! Imagine what happens if y is a 500 -bit number! To make sure the numbers we are dealing with never grow too large, we need to perform all intermediate computations modulo N. So here’s an idea: calculate xy^ mod N by repeatedly multiplying by x modulo N. The resulting sequence of intermediate products,
x mod N → x^2 mod N → x^3 mod N → · · · → xy^ mod N,
30 Algorithms
Figure 1.5 Euclid’s algorithm for finding the greatest common divisor of two numbers.
function Euclid(a, b) Input: Two integers a and b with a ≥ b ≥ 0 Output: gcd(a, b)
if b = 0: return a return Euclid(b, a mod b)
The most obvious approach is to first factor a and b, and then multiply together their common factors. For instance, 1035 = 3^2 · 5 · 23 and 759 = 3 · 11 · 23 , so their gcd is 3 · 23 = 69. However, we have no efficient algorithm for factoring. Is there some other way to compute greatest common divisors?
Euclid’s algorithm uses the following simple formula.
Euclid’s rule If x and y are positive integers with x ≥ y , then gcd(x, y) = gcd(x mod y, y).
Proof. It is enough to show the slightly simpler rule gcd(x, y) = gcd(x − y, y) from which the one stated can be derived by repeatedly subtracting y from x. Here it goes. Any integer that divides both x and y must also divide x − y, so gcd(x, y) ≤ gcd(x − y, y). Likewise, any integer that divides both x − y and y must also divide both x and y, so gcd(x, y) ≥ gcd(x − y, y).
Euclid’s rule allows us to write down an elegant recursive algorithm (Figure 1.5), and its correctness follows immediately from the rule. In order to figure out its running time, we need to understand how quickly the arguments (a, b) decrease with each successive recursive call. In a single round, arguments (a, b) become (b, a mod b): their order is swapped, and the larger of them, a, gets reduced to a mod b. This is a substantial reduction.
Lemma If a ≥ b , then a mod b < a/ 2.
Proof. Witness that either b ≤ a/ 2 or b > a/ 2. These two cases are shown in the following figure. If b ≤ a/ 2 , then we have a mod b < b ≤ a/ 2 ; and if b > a/ 2 , then a mod b = a − b < a/ 2.