RU beehive logo ITEC dept promo banner
ITEC 122
2008fall
ibarland

homeinfolecturesexamsarchive

lect12a
program proof

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 xn." Note how this bridges program-return-values with math (actual exponentiation).

homeinfolecturesexamsarchive


©2008, Ian Barland, Radford University
Last modified 2008.Dec.15 (Mon)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme