Advanced Placement Computer Science AB:
Assignment 21:  Algorithms Revisited
   Sewickley Academy, 2000-2001

See Course Home Page.
 
Date Assigned: Fri Nov-10
Date Due: Tue Nov-14

1.  Read Chapter 9:  Algorithms.

2 (Easy).  Write a program which guesses a number which the user has randomly selected, using binary search for efficiency.  Your program should run as follows:

Think of a number between 0 and 1000 and I will guess it.
I guess your number is 500.  Am I right (0=I am too low, 1=I am too high, 2=I am right): 0
I guess your number is 750.  Am I right (0=I am too low, 1=I am too high, 2=I am right): 1
I guess your number is 625.  Am I right (0=I am too low, 1=I am too high, 2=I am right): 2
Wahoo, I guessed your number in only 3 guesses!
3 (Moderate). Write a similar program as that from #2, but which does not specify a range -- the user can pick any number that can be represented as an "int" by the computer.

4 (Easy).  Rewrite the Greatest Common Factor function gcf(), on page 166, as a recursive function.

5 (Easy).  Recall that each Fibonacci number is the sum of the previous two Fibonacci numbers, so that fib(1) = fib(2) = 1, and for n>2 fib(n) = fib(n-1) + fib(n-2).  Write fib(n) twice, once recursively and once iteratively.  Include it in a main() to get the following behavior:

Enter a number (<=0 to quit): 3
Iterative fib(3) = 2
Recursive fib(3) = 2, and required 3 calls to fib(n)
...
Note:  To compute the recursive call count, you may use a global counter set in main() before calling fib(n) and incremented as the first line in fib(n).

6. (Harder) Read pages 166-167, then write a function PowerOfSum(x,y,n) which returns (x+y)n, then call it from a main() to get the following behavior:

Enter x y n (or 0 0 0 to quit): 2 4 3
(2+4)^3
= (2^3) + 3(2^2)(4) + 3(2)(4^2) + (4^3)
= 8 + 48 + 96 + 64
= 216
...
Hint:  Notice in this example that the exponent is 3 and the corresponding 3rd row of Pascal's Triangle is 1,3,3,1, and those are precisely the coefficients in the first line after (2+4)^3 is output.

Also Note:  Be sure to match this output exactly.

Good luck, and have a grand weekend.



See Course Home Page.