31. Number-Theoretic Algorithms
Exercises
31.1-1
Based on Theorem 31.1 (Division theorem), we have
since . Furthermore, .
31.1-2
Read Euclid's proof on Wikipedia.
31.1-3 🌟
We have and for integers and . Therefore, .
31.1-4
The only divisors of are 1 and . No divisor of except 1 divides , since . Therefore, .
31.1-5
We start from the fact that , thus
31.1-6 🌟
Lemma 1
For any integers and , if for all , then .
Proof We prove the lemma by induction on . The base case trivially holds by Theorem 31.6. For , we have
According to the principles of mathematical induction, we can conclude that the lemma holds for all .
Based on Exercise 31.1-4 and Lemma 1, for , and , so . By Theorem 31.7 we can conclude that . Thus, in a binomial expansion all terms except the first and last one are divisible by , which concludes the proof.
31.1-7
We successively apply the Division theorem, thus
because , so it represents a unique remainder modulo .
For the second part, we get
31.1-8
Assume that multiplication of two -bit integers requires time and equality test of two -bit integers requires time. The algorithm below only showcases an existence of a solution in time polynomial in without claiming anything about its asymptotic optimality. As a matter of fact, it is far from being optimal.
The smallest candidate is and . Therefore, we iterate over all possible exponents in increasing order and see if the th root of is an integer.
We can leverage binary search over the interval in searching for this root. We iteratively raise each candidate to the th power by multiplying the current product with (initially setting it to 1). In each iteration, we also check if this product is greater than , so that we stop as soon as possible. This stage demands time. In case of a match, we finish the search, otherwise, recurse into the lower or upper subinterval depending on whether or not, respectively. If the subinterval becomes empty, then we declare an unsuccessful attempt to find the root for the given exponent.
All in all, we can determine whether a given -bit integer is a nontrivial power in time.
31.1-9
Proof of 31.6
By definition, is the largest element in the set of the common divisors of and . Analogously, is the largest element in the set of the common divisors of and . We know that and there cannot be two different largest element in a set. Therefore, .
Proof of 31.7
, but this also means that , hence . With similar reasoning we can conclude that , therefore .
Proof of 31.8
Proof of 31.9
By property (31.8) we have that . Any common divisor of and 0 cannot be larger than , so (any integer divides 0). As a side note, if then .
Proof of 31.10
By property (31.8) we have that . We have the following three cases:
If then by property (31.9).
If then .
Let . We know that divides itself, and divides . Because is a common divisor, and no divisor of can be strictly greater than , it must be the greatest common divisor. Therefore, .
31.1-10 🌟
Let and . We prove the statement from the book by showing that and , thus by equation (31.5) they must be equal, as both of them are nonnegative.
We know that , which entails that . The fact that divides both and implies that it also divides by Corollary 31.3. Therefore, by applying again Corollary 31.3.
Using the same reasoning we can conclude that , which finishes the proof about associativity of the operator.
★ 31.1-11
You can read the proof here that uses only facts mentioned in the book.
31.1-12
The time algorithm shown here also handles the edge case when a divisor is larger than a number to be divided.
31.1-13
We follow the hint from the book. The main idea is to split a -bit binary number and obtain the top and bottom halves of the result with separate recursions. The divide step must enable an easy assembly of these partial results. Since we are converting into a decimal representation it makes sense to split according to powers of 10. The key insight is to precompute these powers (in binary) to facilitate efficient splitting.
Precomputation is a powerful technique in algorithm design. The steps to accomplish this are laid out below:
Fill the lookup tables
For each level :
Determine the split point (half the digits at level ).
Compute using exponentiation by squaring.
Each has bits, so computing it demands time. The total time is assuming satisfies the properties of standard multiplication algorithms, like, being non-decreasing as well as the sum of over geometrically decreasing sizes is dominated by (sort of weak regularity).
Recursive conversion function
Assume that handling decimal representation is not influencing the asymptotical behavior of our main routine. For example, concatenating strings (and padding with leading zeros) takes linear time with respect to the number of digits. Because is strictly bounded by since , the string operations do not ruin the asymptotic time complexity.
Recursive case
Compute the values for the top and bottom halves.
Recursively obtain the decimal representation of the top half .
Recursively obtain the decimal representation of the bottom half .
Pad with leading zeros to length .
Produce a combined result by concatenating the two halves.
Remove leading zeros from , if any.
Return .
The recurrence formula is . We have two variations on the recurrence using the fact that :
If then by the Master theorem .
If for some then by the Master theorem assuming satisfies the regularity condition (most standard multiplication/division algorithms do).
We can conclude that taking into account the pre-computation and conversion times, too.
31.1-14
See the answer here with a derailed solution.
31.2-1
You can read the proof here. There are two remarks about external references in the content:
Proposition 1(iv) is about the rule .
Proposition 1(i) is Exercise 31.1-3.
31.2-2
We create a table, similar to Figure 31.1 from the book, by running the next Python 3 script.
Observe the usage of the list rows to reverse the output shown below.
31.2-3 🌟
Let and . We proceed by showing that and , thus according to equation (31.5) they are equal.
We know that and , so by equation (31.4) we have . Based on Corollary 31.3 we can conclude that .
We know that , so for some integer . Furthermore, , thus for some integer . Therefore, implies . Based on Corollary 31.3 we can conclude that .
, so by equation (31.18). Consequently, we have .
31.2-4
Below is the iterative version of Euclid's algorithm in Python 3.
31.2-5
If then the call immediately hits the base case and returns, so no recursive calls are made. Assume that .
The steps to prove the first bound are as follows:
Let be the number of recursive calls made by .
By Lamé's theorem, we know that .
By the standard bounds of the Fibonacci sequence, we know that for .
Combining these gives , so .
Let . Because and , the remainder at each step of the algorithm is also perfectly scaled by :
Because every single division operation yields a remainder exactly times larger than the reduced version, the sequence of recursive calls progresses identically. The call will make the exact same number of recursive calls as . Now, proceeding in almost the same way as above, we can establish that the call makes at most recursive calls.
31.2-6
Assume that , otherwise we would immediately reach the base case. , hence by Exercise 31.1-1 we have that . Therefore, the call to recurses into , and this process continues until hitting the base that happens right after the call to . The final call returns a 3-tuple . Thus, . We now need to find out the coefficients and .
In general, returns a 3-tuple . We prove this by induction on . The base case obviously holds. For the quotient . Thus, at all levels. By the inductive hypothesis the call to returns a 3-tuple , thus returns
Observe in line 1 that .
31.2-7
We proceed by induction on . The base cases are when . If then we have nothing to permute and for we can apply equation (31.6).
For assume that the inductive hypothesis holds for arguments. Every permutation is consisted of individual pairwise swaps of elements. An informal indirect proof is an ability of any sorting algorithm to find the matching permutation that results in proper ordering of elements. This is attained in a step-by-step fashion, swapping each time a pair of elements on different positions. Thus, let us consider elements and where . We have two cases:
If then it immediately follows by the inductive hypothesis that .
If then we have the following sequence of equivalent transformations:
Let at some step . Based on Exercise 31.2-5, the number of divisions for this single step is bounded by
Taking into account all steps, we get a telescoping sum
31.2-8 🌟
The base case is defined as (the RHS is an optimization to avoid an overflow error)
The generalization to arbitrary number of arguments is almost the same as with the generic (see the previous exercise). Therefore,
If any , we should immediately halt and return 0.
31.2-9
We first describe the general case and later demonstrate it using the example with from the book. WLOG assume that indices are 0-based.
Proving correctness
If the set of input numbers are pairwise relatively prime, then for . Fix any . Suppose for the sake of contradiction that some prime and . Consequently, there are some distinct numbers and such that and . But that contradicts the initial assumption about our set of input numbers. Thus, no such prime exists, and for all , as our choice of was arbitrary.
If the derived pairs are relatively prime, then for all pairs. Take any two distinct indices and that differ at bit position . WLOG assume that has 1 and has 0. Therefore, and . Suppose for the sake of contradiction that some prime and . But we know that and , so this implies that and . But that contradicts the initial assumption about derived pairs being relatively prime. Therefore, the set of input numbers are pairwise relatively prime, since our choice of indices and was arbitrary.
31.3-1
Here are two possible mappings:
31.3-2
Subgroups of are , and itself. Subgroups of are , , , , and itself.
31.3-3 🌟
We only need to show two things (since associativity is automatically inherited from ):
The identity element .
Every element has its inverse .
Choose any fixed element . Define a modular function such that (see also Exercise 31.3-5). Suppose for some . This means . Because and also belong to the parent group , we know has an inverse . If we left-multiply both sides by , we get . Because , the function is injective. Since is finite, this entails that is surjective, too. In other words, is a bijection.
Because and is bijective, there must be some element that maps to . This gives
In the parent group , the only element that satisfies this equation is the identity element . Therefore, . Since , we have proven that .
Because and is bijective, there must be some element that maps to . This gives
In the parent group , the only element that satisfies this equation is the inverse element . Therefore, . Since , we have proven that .
31.3-4
Apply equation (31.21) to get
31.3-5
We proceed by showing the is a bijection. Any bijection from a set to itself is a permutation of that set. Since the domain and codomain of are of the same cardinality, it is enough to show that is a surjective function.
According to Theorem 31.13, is a finite abelian group. Consequently, . Select any . For , we get
31.4-1
We have , and . The extended version of Euclid's algorithm returns , so and . The step size is , thus all solutions are .
31.4-2
Based on Corollary 31.26, there is a multiplicative inverse , so multiplying both sides of by we get , which implies that .
If , then the previous conclusion is not valid. One counterexample is , where and is also a valid solution.
31.4-3
Yes, it will work, forcing the procedure to emit solutions in sorted order. Among those distinct solutions, which are positions apart from each other, one will always belong to the interval . Let it be for some . Exercise 31.1.-7 implies that , hence setting is the smallest starting value. Since the code starts at the minimum value and adds a positive constant each time without ever wrapping around the modulo boundary, the output is guaranteed to be strictly increasing.
★ 31.4-4 🌟
I recommend reading the proof based on Euclidean division of polynomials, which is aligned with the narrative from the book.
We proceed by induction on degree . The base case follows from Corollary 31.25.
For , we have , so has at most distinct roots modulo (after applying the inductive hypothesis on ). Notice, that any other root of is forced to be a root of . Suppose has another distinct zero , such that and
(recall that is prime). Since , it must be that , so . This concludes the proof for all .
31.5-1
We follow the process outlined in Theorem 31.27. We have , , , , , , , , and . Thus, . All solutions are of the form for arbitrary integers .
31.5-2
We follow the steps outlined in Theorem 31.27. We have , , , , , , , and . Thus, . All solutions are of the form for arbitrary integers .
31.5-3
Let . We simply employ equation (31.30) and Corollary 31.29 to get that has a component-wise modular representation of , where every component is . Therefore, . This correspondence works in both directions.
31.5-4
Let , where all terms of this product are pairwise relatively prime. According to Theorem 31.27, there is a one-to-one correspondence between a root of the equation and its component-wise modular representation. Based on Corollary 31.29, we also have that if and only if for . Furthermore, by the basic rules of modular arithmetic .
Let a -tuple be one solution of the system of equations for . Consequently, computed from inputs , by following the steps from Theorem 31.27, represents a zero of modulo . By the fundamental counting principle, the total number of ways to form a valid -tuple is exactly the product of the number of valid choices for each coordinate. Therefore, the number of roots modulo equals the product of the number of roots modulo each .
31.6-1
1
1
2
10
3
5
4
5
5
5
6
10
7
10
8
10
9
5
10
2
The smallest primitive root is 2 and the indices of are shown below.
1
0
2
1
3
8
4
2
5
4
6
9
7
7
8
3
9
6
10
5
31.6-2
31.6-3
Replace lines 6 and 7 with the following two lines:
31.6-4
Below is the iterative modular repeated squaring algorithm in Python 3.
31.6-5
By Euler's theorem we know that . Therefore, we can calculate the inverse by calling .
31.7-1
, so . The encryption of the message , by equation (31.37), is . You can test that everything is proper by calling (see Exercise 31.6-4) and getting back the original message 100.
31.7-2
Let denote the number of bits in and assume that and are large primes. As , we have that is equivalent to for some integer . Since we know that . We can rewrite the previous expression as . Apparently, and .
We can find . Plugging in into the expression for we get . The last equation can be solved for using the quadratic formula. Obviously, once we have we can trivially find .
All listed steps (including the integer square root) can be executed in time polynomial in , hence the whole process is also doable in time polynomial in .
★ 31.7-3
Suppose an attacker possesses a ciphertext . She/he executes the following procedure to reveal :
Generate a new message .
Compute .
Try to decrypt and store the result into .
If successful, then find modulo and compute .
Goto step 1.
The chance of success at step 3 is 1%. The number of trials follows the geometric distribution with an expected value of 100. Finding inverses modulo is step 4 can be efficiently carried out using the extended Euclid's GCD algorithm. Almost all generated messages at step 1 will be relatively prime to , since the chance of stumbling across one that contains a prime factor of is practically zero. All in all, an attacker can reveal the original message with high probability.
31.8-1
One example is , where 6 is a nontrivial square root of 1 modulo 35, since . Such a root always exists for that satisfies the conditions from this exercise.
Decompose into a product , where and are odd numbers greater than 1 that are relatively prime to each other. By Corollary 31.28, there exists an simultaneously satisfying the equations
Corollary 31.29 gives that . On the other hand, we have
Corollary 31.29 gives that . Therefore, is a nontrivial square root of 1 modulo .
★ 31.8-2
In number theory, is known as the Carmichael function.
Euler’s phi function is a multiplicative function that we can see after substituting to get
It follows that is a multiple of , thus . Another proof, based on group theory, is given here.
Suppose for the sake of contradiction that a Carmichael number is not "square-free," thus it has a factor where . Consequently, . Furthermore, , which is a contradiction with the property that . Therefore, must be "square-free."
Suppose for the sake of contradiction that a Carmichael number is a product of two primes . We have that . On the other hand, because by the Division theorem we have . But this is again a contradiction with the property that . Therefore, must be consisted of at least three primes.
31.8-3
By Exercise 31.6-2 we have . If is a nontrivial square root of 1 modulo , then by Corollary 31.35 is composite, so (you can easily check that produces a prime ). It follows that and , thus prime factors of are distributed between these two terms of a product. Therefore, and are both nontrivial divisors of .
Problems
31-1 Binary gcd algorithm
a.
By Corollary 31.4, we have .
b.
By equation (31.13), doesn't have a prime factor 2. Dividing by 2 reduces the exponent of 2 in , hence making it closer to zero. Consequently, .
c.
Let and . We proceed by showing that and , thus according to equation (31.5) they are equal.
We know that and , so by equation (31.4) we have . Based on Corollary 31.3 we can conclude that
We know that and , so by equation (31.4) we have . Based on Corollary 31.3 we can conclude that .
Since is even and is odd, the division of by 2 is justified according to part (b).
d.
I recommend reading this study of the binary GCD algorithm with insightful C++ based optimizations.
31-2 Analysis of bit operations in Euclid’s algorithm
In all subproblems below assume that , so that .
a.
We do all the arithmetic in binary by processing the bits of from the most significant to the least, accumulating the initial bits of into a value (current residue ) greater or equal than , as they would anyhow produce leading zeros of a quotient.
In the analysis of the long division algorithm, the bits of the quotient and the divisor are counted differently because they play distinct roles. Each bit of is determined in one step of the algorithm. Thus, the number of steps required to compute all bits of is proportional to it's number of bits . This expression is nonzero even if .
At each step, the algorithm performs operations (e.g., comparisons or subtractions) involving the divisor . Since it has approximately bits, these operations require that many bit operations per step. Therefore, the total count is . This complexity reflects that the algorithm's time is dominated by the number of quotient bits (steps) and the size of the divisor (cost per step).
The remainder gets calculated along the way (see also Exercise 31.1-12) and has bits.
b.
The reduction requires us to compute the remainder that can be accomplished in time as given in part (a). We know that , where .
We have proven that .
c.
As shown in part (b), EUCLID takes at most bit operations on the first recursive call, at most on the second, and so on. This sum telescopes, hence we end up with .
When applied to two -bit inputs we get .
31-3 Three algorithms for Fibonacci numbers
a.
The algorithmic recurrence of the running time is . We use a substitution method to prove that this version cannot do better than being exponential in . The constant denotes the lower bound in .
Assume that for .
This concludes the proof, as Fibonacci numbers grow exponentially.
b.
Here is the Python 3 script showcasing memoization. The recurrence resolves to , since memoization prevents repeated work.
It will print in the blink of an eye 354224848179261915075. Try commenting out the annotation to see the difference.
c.
We can leverage the repeated squaring method, with a small change, that instead of multiplying numbers we will work with small constant sized matrices. Each matrix operation will then also take constant time.
We prove the next statement using induction on , following the hint from the book.
The base case obviously holds. For we have
At the end, we need to read out the matching cell containing .
d.
Fibonacci numbers have binary digits, as explained here.
The bare recursive variant still has exponential running time. Increasing the amount of work at each level cannot invalidate the previously established lower bound.
The memoized version has a new recurrence that solves to .
The matrix version employs both addition and multiplication of numbers, hence it has a new recurrence . Case 3 of the master theorem states that .
31-4 Quadratic residues
a.
Theorem 31.32 implies that is a cyclic group, so it has a generator , where all values modulo are distinct for . Every even index is associated with a quadratic residue, since . Thus, the number of quadratic residues is at least .
Suppose for the sake of contradiction that there is also some odd index such that for some . We must have that and . Theorem 31.33 implies that , where . But this is impossible, since due to mismatch in parity. We can conclude that the the number of quadratic residues is exactly .
b.
If is a quadratic residue modulo , then there is an such that
Otherwise, for some odd index (see part(a)). According to Fermat's theorem , so it must be that , as powers of are distinct for . We have
We can call modular_exponentiation(a, (p-1)/2, p) (see Exercise 31.6-4) and check whether the returned value is 1. If we let , then It requires bit operations.
c.
By part (b), , so . Therefore, is a square root of modulo . We can again use modular exponentiation to efficiently find it using bit operations.
d.
Run the algorithm of part (b) by repeatedly trying random numbers until . Half the elements in are not quadratic residues, thus each experiment can be regarded as a Bernoulli trial with probability 1/2. The expected number of trials follows the geometric distribution and equals 2. The average number of arithmetic operations is .
Last updated