// Chap 2, p 71, p 72 // Demonstrates Pow1, Pow2, and Pow3. #include int Pow1(int X, int N) // --------------------------------------------------- // Exponentiation function -- ITERATIVE SOLUTION // Precondition: X is an integer; N is a nonnegative // integer. // Postcondition: Returns X raised to the Nth power. // --------------------------------------------------- { int Temp = 1; for (int Exponent = 1; Exponent <= N; ++Exponent) Temp *= X; return Temp; } // end Pow1 int Pow2(int X, int N) // Exponentiation function -- RECURSIVE SOLUTION { if (N == 0) return 1; else return X * Pow2(X, N-1); } // end Pow2 int Pow3(int X, int N) // Exponentiation function -- MORE EFFICIENT // RECURSIVE SOLUTION { if (N == 0) return 1; else { int HalfPower = Pow3(X, N/2); if (N % 2 == 0) return HalfPower * HalfPower; // even N else return X * HalfPower * HalfPower; // odd N } // end else } // end Pow3 // ******SAMPLE MAIN PROGRAM****** main() { int Number, Result1, Result2, Result3, Power; char Response; do { cout << "\n\nEnter an integer, a space, and an integer exponent: "; cin >> Number >> Power; Result1 = Pow1(Number, Power); Result2 = Pow2(Number, Power); Result3 = Pow3(Number, Power); cout << "\n" << Number << " to the " << Power << " is\n"; cout << " " << Result1 << " using Pow1\n"; cout << " " << Result2 << " using Pow2\n"; cout << " " << Result3 << " using Pow3\n\n"; cout << "Continue? "; cin >> Response; } while ((Response != 'n') && (Response != 'N')); return(0); } // end program