Powers

Pseudo-code

  1. The base case $$n = 0$$, and $$x^0 = 1$$
  2. If $$n$$ is positive compute recursively $$y=x^{(n/2)}$$
  3. If $$n$$ is positive and odd, recursively compute $$x^{(n - 1)}$$
  4. If $$n$$ is negative, compute $$x^{-n}$$ until n is positive. Then $$x^n = 1/x^{-n}$$

Implementation

  1. var isEven = function(n) {
  2. return n % 2 === 0;
  3. };
  4. var isOdd = function(n) {
  5. return !isEven(n);
  6. };
  7. var power = function(x, n) {
  8. println("Computing " + x + " raised to power " + n + ".");
  9. // base case
  10. if(n === 0) {
  11. return 1;
  12. }
  13. // recursive case: n is negative
  14. if(n < 0) {
  15. return 1 / power(x, -n);
  16. }
  17. // recursive case: n is odd
  18. if(isOdd(n)) {
  19. return x * power(x, n - 1);
  20. }
  21. // recursive case: n is even
  22. if(isEven(n)) {
  23. var y = power(x, n/2);
  24. return y * y;
  25. }
  26. };
  27. var displayPower = function(x, n) {
  28. println(x + " to the " + n + " is " + power(x, n));
  29. };
  30. displayPower(3, 0);
  31. Program.assertEqual(power(3, 0), 1);
  32. displayPower(3, 1);
  33. Program.assertEqual(power(3, 1), 3);
  34. displayPower(3, 2);
  35. Program.assertEqual(power(3, 2), 9);
  36. displayPower(3, -1);
  37. Program.assertEqual(power(3, -1), 1/3);
  38. Program.assertEqual(power(4, -1), 1/4);
  39. Program.assertEqual(power(5, -5), Math.pow(5, -5));