← Recursion

Power Function

Easy
Python
def my_pow(x,n):
    if n==0: return 1
    if n<0: return 1/my_pow(x,-n)
    if n%2==0: return my_pow(x*x,n//2)
    return x*my_pow(x,n-1)
Java
public double myPow(double x,int n){
    if(n==0) return 1;
    if(n<0) return 1/myPow(x,-n);
    if(n%2==0) return myPow(x*x,n/2);
    return x*myPow(x,n-1);
}

Key Insight

Fast power. Python handles negatives cleanly. Java needs explicit double type.

Python → Java Differences

  • Python handles negatives cleanly
  • Java needs double return type
  • Fast exponentiation identical
Python
def my_pow(x,n):
    if n==0: return 1
    if n<0: return 1/my_pow(x,-n)
    if n%2==0: return my_pow(x*x,n//2)
    return x*my_pow(x,n-1)
Java
public double myPow(double x,int n){
    if(n==0) return 1;
    if(n<0) return 1/myPow(x,-n);
    if(n%2==0) return myPow(x*x,n/2);
    return x*myPow(x,n-1);
}

Algorithm Steps

1. Base: n==0 -> 1
2. Negative: reciprocal
3. Even: square x halve n