<AI/>
enru
Все статьи

Pow(x, n)

LeetCode 50: Implement exponentiation from brute force to fast O(log n) binary exponentiation.

Сложность
Средняя
Автор
Denis Kolpakov
Опубликовано
Темы
#math#recursion
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

Write a function that raises a number x to the power n.

Input: x (a floating-point number), n (an integer)

Output: a floating-point number: the result of raising x to the power n

Constraints

  • -100.0 < x < 100.0
  • -231 <= n <= 231-1
  • -104 <= xn <= 104
  • When x = 0, n is non-negative

Examples

Input

x = 2.00000
n = 10

Answer: 1024.00000

Brute force approach

Since exponentiation is multiplying x by itself n times, a brute force solution can be written with a plain loop (for now, let's assume n is always > 0):

typescript
let res = x;
 
for (; n > 1; n--) {
  res *= x;
}
 
return res;

To handle negative n, let's recall a property of powers: x-n = 1 / xn.

So we move raising to a positive power into a separate function.

typescript
const powAbsNBruteforce = (x: number, n: number): number => {
  if (n === 0) {
    return 1;
  }
 
  if (n === 1) {
    return x;
  }
 
  let res = x;
 
  for (; n > 1; n--) {
    res *= x;
  }
 
  return res;
};

And in the main function we add a check for negative n.

typescript
if (n < 0) {
  return 1 / powAbsNBruteforce(x, -1 * n);
}
 
return powAbsNBruteforce(x, n);

The final solution:

typescript
const powAbsNBruteforce = (x: number, n: number): number => {
  if (n === 0) {
    return 1;
  }
 
  if (n === 1) {
    return x;
  }
 
  let res = x;
 
  for (n; n > 1; n--) {
    res *= x;
  }
 
  return res;
};
 
export const myPowBruteforce = (x: number, n: number): number => {
  if (x === 1) {
    return 1;
  }
 
  if (x == -1) {
    if (n % 2 === 0) {
      return 1;
    }
 
    return -1;
  }
 
  let res: number;
 
  if (n < 0) {
    res = 1 / powAbsNBruteforce(x, -1 * n);
  } else {
    res = powAbsNBruteforce(x, n);
  }
 
  return parseFloat(res.toFixed(5));
};

Complexity Analysis

Time Complexity

To compute the power we need n multiplications, so the complexity is O(n).

Space Complexity

O(1): the additional memory is constant.

Optimal approach

We can reduce the number of multiplications by recalling another property of powers: xn = (x * x)n/2.

For example, 28 = 44 = 162 = 256.

So we can rewrite our function recursively, remembering to handle odd powers separately:

typescript
const powAbsN = (x: number, n: number): number => {
  if (n === 0) {
    return 1;
  }
 
  if (n === 1) {
    return x;
  }
 
  if (n % 2 != 0) {
    return powAbsN(x * x, Math.floor(n / 2)) * x;
  }
 
  return powAbsN(x * x, Math.floor(n / 2));
};
 
export const myPow = (x: number, n: number): number => {
  if (x === 1) {
    return 1;
  }
 
  if (x === -1) {
    if (n % 2 === 0) {
      return 1;
    }
 
    return -1;
  }
 
  let res: number;
 
  if (n < 0) {
    res = 1 / powAbsN(x, -1 * n);
  } else {
    res = powAbsN(x, n);
  }
 
  return parseFloat(res.toFixed(5));
};

Complexity Analysis

Time Complexity

With this approach, every recursion step squares the number, halving the number of required multiplications. So the overall complexity is O(log n).

Space Complexity

O(log n): the depth of the recursion stack.