3.3. Exercises

3-1.Unlike languages designed for scientific computation, Java contains no operator to raise a number to a given power, although it does have a function in the Math class that accomplishes the task. Assuming that the exponent k is always a nonnegative integer, write a recursive function power(x, k) that raises the real value x to the k power.
3-2.Without using the explicit formula, write a recursive function that computes the answer to the "cannonball" problem from exercise 2-3 on page 27.
3-3.As illustrated in Chapter 2, the sum of the first N odd integers has the value N2. This observation makes it easy to write a recurrence relation that defines the square of an integer in terms of the square of the previous integer. Write out this recurrence relation, and, by adding an appropriate simple case, complete the definition of the Java function
int square(int n)
that squares its argument.
3-4.The greatest common divisor of two nonnegative integers x and y is defined to be the largest integer that divides evenly into both. For example, given the numbers 28 and 63, the greatest common divisor is 7. This problem was considered to be of great importance to classical mathematicians, including Euclid, whose Elements (book 7, proposition II) contains an elegant solution. The essence of Euclid's discovery is that the greatest common divisor of x and y must always be the same as that of y and r, where r is the remainder of x divided by y. By providing an appropriate simple case, ...

Get Thinking Recursively with Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.