public class power_r { // there's another way to compute those powers! // let's see... // square -> same as in power_i public static int pow2(int x) { return x * x; } // cube -> look: x^3 = x * x^2, so we can make use of pow2() public static int pow3(int x) { return x * pow2(x); } // 4th power -> idem: x^4 = x * x^3 public static int pow4(int x) { return x * pow3(x); } // generalization: n-th power -> x^n = x * x^(n - 1) // (works for n > 0) public static int pown(int x, int n) { if (n == 1) { return x; } return x * pown(x, n - 1); } ///////////////////////////////////////////////////////////////////// // now, pown() doesn't contain any loops! // // // // this is a RECURSIVE solution, whereas what we've done for // // power_i.java is called an ITERATIVE solution. // // // // as a matter of fact, every iterative procedure can be // // written recursively and vice-versa - // // however, often one way to write a procedure is much more // // easy than the other (see for example the flood-fill exercise // // from the ITP labs) // ///////////////////////////////////////////////////////////////////// // test our methods -> still works ;-) public static void main(String a[]) { System.out.println(" 7^2 = " + pow2(7)); System.out.println("10^3 = " + pow3(10)); System.out.println(" 2^4 = " + pow4(2)); System.out.println(" 2^5 = " + pown(2, 5)); } }