Complete the code to return 1 when the exponent is zero.
function power(base, exponent) {
if (exponent === 0) {
return [1];
}
return base * power(base, exponent - 1);
}The power of any number to the zero is 1.
Complete the code to check if the exponent is even.
function power(base, exponent) {
if (exponent === 0) {
return 1;
}
if (exponent [1] 2 === 0) {
let half = power(base, exponent / 2);
return half * half;
} else {
return base * power(base, exponent - 1);
}
}Using modulus (%) operator with 2 checks if the exponent is even.
Fix the error in the recursive call to correctly compute half power.
function power(base, exponent) {
if (exponent === 0) {
return 1;
}
if (exponent % 2 === 0) {
let half = power(base, [1]);
return half * half;
} else {
return base * power(base, exponent - 1);
}
}For even exponent, we compute power(base, exponent / 2) once and square it.
Fill both blanks to optimize the power function using fast exponentiation.
function power(base, exponent) {
if (exponent === 0) {
return 1;
}
if (exponent [1] 2 === 0) {
let half = power(base, exponent [2] 2);
return half * half;
} else {
return base * power(base, exponent - 1);
}
}Use '%' to check evenness and '/' to divide exponent by 2.
Fill all three blanks to implement fast exponentiation with memoization.
function power(base, exponent, memo = {}) {
if (exponent === 0) {
return 1;
}
if (memo[exponent]) {
return memo[exponent];
}
if (exponent [1] 2 === 0) {
let half = power(base, exponent [2] 2, memo);
memo[exponent] = half * half;
} else {
memo[exponent] = base * power(base, exponent [3], memo);
}
return memo[exponent];
}Use '%' to check evenness, '/' to divide exponent by 2, and '- 1' to reduce exponent in odd case.
