Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a recursive function power(x, n) that returns the value of x^n. (assume th

ID: 3932985 • Letter: W

Question

Write a recursive function power(x, n) that returns the value of x^n.
(assume that n is an integer)

Start by writing the base case.

Once implemented, uncomment the relevant displayPower() to see how the result is computed, and uncomment the relevant Program.assertEqual() to make sure the test passes.

HINT:

---------------------------------------------------------

var isEven = function(n) {
return n % 2 === 0;
};

var isOdd = function(n) {
return !isEven(n);
};

var power = function(x, n) {
println("Computing " + x + " raised to power " + n + ".");
// base case
// recursive case: n is negative
// recursive case: n is odd
// recursive case: n is even
};

var displayPower = function(x, n) {
println(x + " to the " + n + " is " + power(x, n));
};

//displayPower(3, 0);
//Program.assertEqual(power(3, 0), 1);
//displayPower(3, 1);
//Program.assertEqual(power(3, 1), 3);
//displayPower(3, 2);
//Program.assertEqual(power(3, 2), 9);
//displayPower(3, -1);
//Program.assertEqual(power(3, -1), 1/3);

Explanation / Answer

var power = function(x, n) {
if(n == 0) //base case is x^0. In this case x^0 is 1.
return 1;
else //rest of the cases just multiply by x and decrement n to call power function again.
return x * power(x, n-1);
};

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote