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
- -100.0 < x < 100.0
- -2³¹ ≤ n ≤ 2³¹ − 1
- x ≠ 0 or n > 0
- -10⁴ ≤ xⁿ ≤ 10⁴
Edge cases to test
- n = 0:
1 - Negative n: use 1 / x
n = −2³¹(negating overflows in 32 bits)
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 resultC++
#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
- Plus One (Easy)
- Happy Number (Easy)
- GCD and LCM (Euclid) (Easy)
- Count Primes (Sieve of Eratosthenes) (Medium)
- Count Good Numbers (mod 1e9+7) (Medium)
- Multiply Strings (Medium)
- Reverse Integer (Medium)
- String to Integer (atoi) (Medium)
- Detect Squares (Medium)
- Random Pick with Weight (Medium)
- Shuffle an Array (Medium)
- Linked List Random Node (Medium)
- Pascal's Triangle (Easy)
- nCr mod p (Medium)
- Max Points on a Line (Hard)