function power(base: number, exponent: number): number {
if (exponent === 0) return 1;
let half = power(base, Math.floor(exponent / 2));
if (exponent % 2 === 0) {
return half * half;
} else {
return half * half * base;
}
}
console.log(power(3, 5));The function uses fast exponentiation by dividing the exponent by 2 recursively. 3^5 = 3 * 3^4 = 3 * (3^2)^2 = 3 * (9)^2 = 3 * 81 = 243.
Each recursive call halves the exponent, so the number of calls is proportional to log base 2 of the exponent. Hence, the time complexity is O(log n).
function power(base: number, exponent: number): number {
if (exponent === 0) return 1;
let half = power(base, exponent / 2);
if (exponent % 2 === 0) {
return half * half;
} else {
return half * half * base;
}
}
console.log(power(2, 3));The recursive call uses exponent / 2 which produces a floating-point number. The base case checks for exponent === 0, but exponent never becomes exactly 0 due to fractional values, causing infinite recursion and stack overflow.
Option B correctly handles the base case, uses Math.floor to keep exponent integer, and applies modulo at every multiplication step to avoid overflow.
function fastPower(base: number, exponent: number): number {
if (exponent === 0) return 1;
let half = fastPower(base, Math.floor(exponent / 2));
if (exponent % 2 === 0) {
return half * half;
} else {
return half * half * base;
}
}
console.log(fastPower(2, 10));2^10 equals 1024. The function uses fast exponentiation correctly to compute this value.
