Algo-Sim › Math & Geometry

Pow(x, n)

Medium · Math & Geometry · step through it in Java, Python and C++ on your own input

Fast exponentiation: square the base once per bit of n and multiply in the powers whose bit is 1. O(log n) instead of O(n).

Problem

Implement pow(x, n), which returns x raised to the power n. n may be negative (then the answer is 1 / x^|n|) and may be as large as a 32-bit integer, so multiplying one step at a time is too slow.

Constraints

Edge cases to test

Follow-up questions

How do you handle n = −2³¹?
Convert n to a 64-bit long before negating, or recurse on n / 2 without negating the whole value.
Where else is fast power used?
Modular exponentiation in hashing and cryptography, and matrix powers for Fibonacci-style recurrences in O(k³ log n).

Solution

Java

public double myPow(double x, int n) {
    long N = n;
    if (N < 0) {
        x = 1 / x;
        N = -N;
    }
    double result = 1;
    while (N > 0) {
        if ((N & 1) == 1) result *= x;
        x *= x;
        N >>= 1;
    }
    return result;
}

Python

def my_pow(x, n):
    N = n
    if N < 0:
        x = 1 / x
        N = -N
    result = 1.0
    while N > 0:
        if N & 1:
            result *= x
        x *= x
        N >>= 1
    return result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    double myPow(double x, int n) {
        long long N = n;
        if (N < 0) {
            x = 1 / x;
            N = -N;
        }
        double result = 1;
        while (N > 0) {
            if ((N & 1) == 1)
                result *= x;
            x *= x;
            N >>= 1;
        }
        return result;
    }
};

More Math & Geometry problems