/* * Compute x^n using repeated squaring. * * Version 1: inefficient, since each call makes *2* recursive calls */ static public int pow(int x, int n) { if (n == 0) return 1; if (n%2 == 0) { /* n is even */ return pow(x, n/2) * pow (x, n/2); } else { /* n is odd, so n/2 rounds down */ /* thus, x^11 = x^5 * x^5 * x */ return pow(x, n/2) * pow (x, n/2) * x; } } /* * Compute x^n using repeated squaring. * * Version 2: efficient, each call makes *1* recursive call, * and reuses the result of that call. */ static public int pow(int x, int n) { if (n == 0) return 1; int halfway = pow (x, n/2); if (n%2 == 0) { /* n is even */ return halfway * halfway; } else { /* n is odd */ return halfway * halfway * x; } } /* Our textbook devises a different solution on pp. 47-48. */