Strong induction to prove the correctness of this code:


// Return x^n.
//
double pow( double x, int n ) {
  if (n==0) {
    return 1;
    }
  else {
    if (n%2==0) {
      return sqr( pow(x,n/2) );
      }
    else {
      return sqr( pow(x,n/2) ) * x;
      }
    }
  }

// Return x^2.
double sqr( double x ) { return x*x; }


(Note that this program can be written more concisely:)

// Return x^n.
//
double pow( double x, int n ) {
  return (n==0) ? 1 : sqr(pow(x,n/2)) * (n%2==0 ? 1.0 : x);
  }


Let P(n) be:
"For any x, pow(x,n) really does return x."
Note how this bridges program-return-values with math (actual exponentiation).


  
    Base case: P(0) = "For any x, pow(x,0) returns x".
    Well, by inspection of our code (and the meaning of Java's 'if'),
    our code returns 1.  Is that x?
    (Hmm, it is except for when x=0…)
  
  
    Induction step: We must show that, ∀k≥0,
    P(0)…P(k) → P(k+1).
    That is, we want to conclude P(k+1) = "∀x, pow(x,k+1) 
    returns x.
    
We consider two cases: Case k+1 is even (that is, k+1=2m, for some m<k+1): Then, k+1 % 2 == 0 (since k+1 even), our code returns sqr(pow(x,(k+1)/2)). By our inductive hypothesis, P((k+1)/2), we know that pow(x,(k+1)/2) = x, so sqr(pow(x,(k+1)/2)) = sqr(x) = x * x (by the meaning of calling sqr), = x, as desired. Case k+1 is odd (that is, k+1=2m+1, for some m<k+1):