Chapter Questions
Give an example of a set of steps that conforms to the informal definition of an algorithm given in the opening paragraph of Section 5.1 but does not conform to the formal definition given in Figure 5.1.
Explain the distinction between an ambiguity in a proposed algorithm and an ambiguity in the representation of an algorithm.
Describe how the use of primitives helps remove ambiguities in an algorithm's representation.
Select a subject with which you are familiar and design a pseudocode for giving directions in that subject. In particular, describe the primitives you would use and the syntax you would use to represent them. (If you are having trouble thinking of a subject, try sports, arts, or crafts.)
Does the following program represent an algorithm in the strict sense? Why or why not?Count $\leftarrow 0$;while (Count not 5 ) do(Count $\leftarrow$ Count +2$)$
In what sense do the following three steps not constitute an algorithm?Step 1: Draw a straight line segment between the points with rectangular coordinates $$(2,5)$$ and $$(6,11)$$.Step 2: Draw a straight line segment between the points with rectangular coordinates $$(1,3)$$ and $$(3,6$)$.Step 3: Draw a circle whose center is at the intersection of the previous line segments and whose radius is two.
Rewrite the following program segment using a repeat structure rather than a while structure. Be sure the new version prints the same values as the original.Count $\leftarrow 2$;while (Count < 7) do(print the value assigned to Count and Count $\leftarrow$ Count +1 )
Rewrite the following program segment using a while structure rather than a repeat structure. Be sure the new version prints the same values as the original.Count $\leftarrow 1$;repeat(print the value assigned to Count andCount $\leftarrow$ Count +1$)$until (Count $=5)$Count $\leftarrow 1$;repeat(print the value assigned to Count andCount $\leftarrow$ Count +1$)$until (Count $=5$ )
What must be done to translate a posttest loop expressed in the formrepeat (. . .) until $(. .$.$)$into an equivalent posttest loop expressed in the formdo $(. .$.$)$ while $(. . $.$)$
Design an algorithm that, when given an arrangement of the digits $0,1,2,3,4,5,6,7$, 8,9 , rearranges the digits so that the new arrangement represents the next larger value that can be represented by these digits (or reports that no such rearrangement exists if no rearrangement produces a larger value). Thus 5647382901 would produce 5647382910.
Design an algorithm for finding all the factors of a positive integer. For example, in the case of the integer 12 , your algorithm should report the values $1,2,3,4,6$, and 12 .
Design an algorithm for determining the day of the week of any date since January 1,1700 . For example, August 17, 2001 was a Friday.
What is the difference between a formal programming language and a pseudocode?
What is the difference between syntax and semantics?
The following is an addition problem in traditional base ten notation. Each letter represents a different digit. What digit does each letter represent? How did you get your foot in the door?$$\begin{array}{r}X Y Z \\+\quad Y W Y \\\hline Z Y Z W\end{array}$$
The following is a multiplication problem in traditional base ten notation. Each letter represents a different digit. What digit does each letter represent? How did you get your foot in the door?$$\begin{array}{r}X Y \\\times Y X \\\hline X Y \\Y Z \\\hline W V Y\end{array}$$
The following is an addition problem in binary notation. Each letter represents a unique binary digit. Which letter represents 1 and which represents 0 ? Design an algorithm for solving problems like this.$$\begin{array}{r}Y X X \\+\quad X Y X \\\hline X Y Y Y\end{array}$$
Four prospectors with only one lantern must walk through a mine shaft. At most, two prospectors can travel together and any prospector in the shaft must be with the lantern. The prospectors, named Andrews, Blake, Johnson, and Kelly, can walk through the shaft in one minute, two minutes, four minutes, and eight minutes, respectively. When two walk together they travel at the speed of the slower prospector. How can all four prospectors get through the mine shaft in only 15 minutes? After you have solved this problem, explain how you got your foot in the door.
Starting with a large wine glass and a small wine glass, fill the small glass with wine and then pour that wine into the large glass. Next, fill the small glass with water and pour some of that water into the large glass. Mix the contents of the large glass, and then pour the mixture back into the small glass until the small glass is full. Will there be more water in the large glass than there is wine in the small glass? After you have solved this problem, explain how you got your foot in the door.
Two bees, named Romeo and Juliet, live in different hives but have met and fallen in love. On a windless spring morning, they simultaneously leave their respective hives to visit each other. Their routes meet at a point 50 meters from the closest hive, but they fail to see each other and continue on to their destinations. At their destinations, they spend the same amount of time to discover that the other is not home and begin their return trips. On their return trips, they meet at a point that is 20 meters from the closest hive. This time they see each other and have a picnic lunch before returning home. How far apart are the two hives? After you have solved this problem, explain how you got your foot in the door.
Design an algorithm that, given two strings of characters, tests whether the first string appears as a substring somewhere in the second.
The following algorithm is designed to print the beginning of what is known as the Fibonacci sequence. Identify the body of the loop. Where is the initialization step for the loop control? The modification step? The test step? What list of numbers is produced?Last $\leftarrow 0 ;$Current $\leftarrow 1$;while (Current $<100$ ) do(print the value assigned to Current;Temp $\leftarrow$ Last;Last $\leftarrow$ Current; andCurrent $\leftarrow$ Last + Temp)Last $\leftarrow 0$;Current $\leftarrow 1$;while (Current < 100) do(print the value assigned to Current;Temp $\leftarrow$ Last;Last $\leftarrow$ Current; andCurrent $\leftarrow$ Last + Temp)
What sequence of numbers is printed by the following algorithm if it is started with input values 0 and 1 ?procedure MysteryWrite (Last, Current) if (Current $<100$ ) then(print the value assigned to Current; Temp $\leftarrow$ Current + Last;apply MysteryWrite to the values Current and Temp)
Modify the procedure MysteryWrite in the preceding problem so that the values are printed in reverse order.
What letters are interrogated by the binary search (Figure 5.14) if it is applied to the list A, B, C, D, E, F, G, H, I, J, K, L, M, N, O when searching for the value J? What about searching for the value $\mathrm{Z}$ ?
After performing many sequential searches on a list of 6,000 entries, what would you expect to be the average number of times that the target value would have been compared to a list entry? What if the search algorithm was the binary search?
Identify the termination condition in each ofthe following iterative statements.a. while (Count < 5) do ( )b. repeat ( ) until (Count = 1)c. while ((Count < 5) and (Total < 56)) do ( )
Identify the body of the following loop structure and count the number of times it will be executed. What happens if the test is changed to read "(Count not 6$)^n$ ?Count $\leftarrow 1$while (Count not 7 ) do(print the value assigned to Count andCount $\leftarrow$ Count +3 )
What problems do you expect to arise if the following program is implemented on a computer? (Hint: Remember the problem of round-off errors associated with floating-point arithmetic.)Count $\leftarrow$ one-tenth;repeat$\quad$ (print the value assigned to Count andCount $\leftarrow$ Count + one-tenth)until (Count equals 1 )Count $\leftarrow$ one-tenth;repeat(print the value assigned to count andCount $\leftarrow$ Count + one-tenth)until (Count equals 1)
Design a recursive version of the Euclidean algorithm (Question 3 of Section 5.2).
Suppose we apply both Test1 and Test2 (defined below) to the input value 1 . What is the difference in the printed output of the two routines?procedure Test1 (Count)if (Count not 5 )then (print the value assigned to Count;apply Test1 to the valueCount +1 )procedure Test1 (Count)if (Count not 5 )then (print the value assigned to Count;apply Test1 to the valueCount +1 )procedure Test2 (Count)if (Count not 5 )then (apply Test2 to the valueCount $+1 ;$print the value assigned toCount)procedure Test2 (Count)if (Count not 5)then (apply Test2 to the valueCount +1print the value assigned toCount)
Identify the important constituents of the control mechanism in the routines of the previous problem. In particular, what condition causes the process to terminate? Where is the state of the process modified toward this termination condition? Where is the state of the control process initialized?
Identify the termination condition in the following recursive procedure.procedure $X X X \quad(\mathrm{~N})$if $(N=5)$ then (apply the procedure $X X X$ to the value $N+1$ )
Apply the procedure MysteryPrint (defined below) to the value 3 and record the values that are printed.procedure MysteryPrint (N)if $(N>0)$ then (print the value of $N$ and apply the procedure MysteryPrint to the value $N-2$ )Print the value of $N+1$.
Apply the procedure MysteryPrint (defined below) to the value 2 and record the values that are printed.procedure MysteryPrint (N)if $(\mathrm{N}>0)$then (print the value of $N$ and apply the procedure MysteryPrint to the value $N-2$ )else (print the value of $N$ and if $(N>-1)$then (apply the procedure MysteryPrintto the value $N+1$ ))
Design an algorithm to generate the sequence of positive integers (in increasing order) whose only prime divisors are 2 and 3 ; that is, your program should produce the sequence 2 , $3,4,6,8,9,12,16,18,24,27, \ldots$. Does your program represent an algorithm in the strict sense?
Answer the following questions in terms of the list: Alice, Byron, Carol, Duane, Elaine, Floyd, Gene, Henry, Iris.a. Which search algorithm (sequential or binary) will find the name Gene more quickly?b. Which search algorithm (sequential or binary) will find the name Alice more quickly?c. Which search algorithm (sequential or binary) will detect the absence of the name Bruce more quickly?d. Which search algorithm (sequential or binary) will detect the absence of the name Sue more quickly?e. How many entries will be interrogated when searching for the name Elaine when using the sequential search? How many will be interrogated when using the binary search?
The factorial of 0 is defined to be 1 . The factorial of a positive integer is defined to be the product of that integer times the factorial of the next smaller nonnegative integer. We use the notation $n$ ! to express the factorial of the integer $n$. Thus the factorial of 3 (written 3 !) is $3 \times(2 !)=3 \times(2 \times(1 !))=3 \times(2 \times(1 \times(0 !)))=$ $3 \times(2 \times(1 \times(1)))=6$. Design a recursive algorithm that computes the factorial of a given value.
a. Suppose you must sort a list of five names, and you have already designed an algorithm that sorts a list of four names. Design an algorithm to sort the list of five names by taking advantage of the previously designed algorithm.b. Design a recursive algorithm to sort arbitrary lists of names based on the technique used in (a).
The puzzle called the Towers of Hanoi consists of three pegs, one of which contains several rings stacked in order of descending diameter from bottom to top. The problem is to move the stack of rings to another peg. You are allowed to move only one ring at a time, and at no time is a ring to be placed on top of a smaller one. Observe that if the puzzle involved only one ring, it would be extremely easy. Moreover, when faced with the problem of moving several rings, if you could move all but the largest ring to another peg, the largest ring could then be placed on the third peg, and then the problem would be to move the remaining rings on top of it. Using this observation, develop a recursive algorithm for solving the Towers of Hanoi puzzle for an arbitrary number of rings.
Another approach to solving the Towers of Hanoi puzzle (Problem 40) is to imagine the pegs arranged on a circular stand with a peg mounted at each of the positions of 4,8 , and 12 o'clock. The rings, which begin on one of the pegs, are numbered $1,2,3$, and so on, starting with the smallest ring being 1 . Oddnumbered rings, when on top of a stack, are allowed to move clockwise to the next peg; likewise, even-numbered rings are allowed to move counterclockwise (as long as that move does not place a ring on a smaller one). Under this restriction, always move the largest-numbered ring that can be moved. Based on this observation, develop a nonrecursive algorithm for solving the Towers of Hanoi puzzle.
Develop two algorithms, one based on a loop structure and the other on a recursive structure, to print the daily salary of a worker who each day is paid twice the previous day's salary (starting with one penny for the first day's work) for a 30-day period. What problems relating to number storage are you likely to encounter if you implement your solutions on an actual machine?
Design an algorithm to find the square root of a positive number by starting with the number itself as the first guess and repeatedly producing a new guess from the previous one by averaging the previous guess with the result of dividing the original number by the previous guess. Analyze the control of this repetitive process. In particular, what condition should terminate the repetition?
Design an algorithm that lists all possible rearrangements of the symbols in a string of five distinct characters.
Design an algorithm that, given a list of names, finds the longest name in the list. Determine what your solution does if there are several "longest" names in the list. In particular, what would your algorithm do if all the names had the same length?
Design an algorithm that, given a list of five or more numbers, finds the five smallest and five largest numbers in the list without sorting the entire list.
Arrange the names Brenda, Doris, Raymond, Steve, Timothy, and William in an order that requires the least number of comparisons when sorted by the insertion sort algorithm (Figure 5.11).
What is the largest number of entries that are interrogated if the binary search algorithm (Figure 5.14) is applied to a list of 4000 names? How does this compare to the sequential search (Figure 5.6)?
Use big-theta notation to classify the traditional grade school algorithms for addition and multiplication. That is, if asked to add two numbers each having $n$ digits, how many individual additions must be performed. If requested to multiply two $n$-digit numbers, how many individual multiplications are required?
Sometimes a slight change in a problem can significantly alter the form of its solution. For example, find a simple algorithm for solving the following problem and classify it using bigtheta notation:Divide a group of people into two disjoint subgroups (of arbitrary size) such that the difference in the total ages of the members of the two subgroups is as large as possible.
From the following list, extract a collection of numbers whose sum is 3165 . How efficient is your approach to the problem?$$26,39,104,195,403,504,793,995,1156,1677$$
Does the loop in the following routine terminate? Explain your answer. Explain what might happen if this routine is actually executed by a computer (refer to Section 1.7).$X \leftarrow 1 ;$$Y \leftarrow 1 / 2 ;$while $(X$ not equal 0$)$ do$\quad(X \leftarrow X-Y ;$$Y \leftarrow Y \div 2)$$X \leftarrow 1$$Y \leftarrow 1 / 2$while ( $X$ not equal 0$)$ do$(\mathrm{X} \leftarrow \mathrm{X}-\mathrm{Y} ;$$Y \leftarrow Y \div 2)$
The following program segment is designed to compute the product of two nonnegative integers $X$ and $Y$ by accumulating the sum of $X$ copies of $Y$; that is, 3 times 4 is computed by accumulating the sum of three $4 \mathrm{~s}$. Is the program segment correct? Explain your answer.Product $\leftarrow 0 ;$Count $\leftarrow 0$;repeat (Product $\leftarrow$ Product $+\mathrm{Y}$,$\quad$ Count $\leftarrow$ Count +1 )until (Count $=\mathrm{X}$ )
The following program segment is designed to report which of the positive integers $\mathrm{X}$ and $\mathrm{Y}$ is larger. Is the program segment correct? Explain your answer.Difference $\leftarrow \mathrm{X}-\mathrm{Y}$;if (Difference is positive)then (print " $X$ is bigger than $Y "$ ")else (print " $Y$ is bigger than $X "$ )
The following program segment is designed to find the largest entry in a nonempty list of integers. Is it correct? Explain your answer.TestValue $\leftarrow$ first list entry;Currententry $\leftarrow$ first list entry;while (Currententry is not the last entry) do(if (CurrentEntry > TestValue)then (TestValue $\leftarrow$ CurrentEntry)CurrentEntry $\leftarrow$ the next list entry)
a. Identify the preconditions for the sequential search as represented in Figure 5.6. Establish a loop invariant for the while structure in that program that, when combined with the termination condition, implies that upon termination of the loop, the algorithm will report success or failure correctly.b. Give an argument showing that the while loop in Figure 5.6 does in fact terminate.
Based on the preconditions that $X$ and $Y$ are assigned nonnegative integers, identify a loop invariant for the following while structure that, when combined with the termination condition, implies that the value associated with $Z$ upon loop termination must be $X-Y$.$Z \leftarrow X$$J \leftarrow 0 ;$while $(J<Y)$ do$\quad(Z \leftarrow Z-1 ;$$J \leftarrow J+1)$$\mathrm{Z} \leftarrow \mathrm{X}$$J \leftarrow 0$;while $(J<Y)$ do$(Z \leftarrow Z-1$;$J \leftarrow J+1)$