/* ---------- Example Iterative function to raise a double x to a positive power n. Uses bitwise operations to check parity (even/odd) and to divide by 2, thus explicitly avoiding extra divisions. Note that n is odd if and only if the 1's bit in its binary representation is 1 and not zero. Thus, if the bitwise AND operator & is applied to n and the number 1, the result will be zero if n is even and 1 if n is odd. Let y be a binary digit, so that y is zero or 1. Then: xxxxxxxxxxy & 00000000001 ----------- = 0000000000y (The values of the 'x' digits are irrelevant.) ---------- */ #include #include using namespace std; double intPower( double x, unsigned int n ) { assert ( n >= 0 ); if ( n == 1 ) return x; else if (n == 0) return 1.0; // base cases. double prod = 1, power2 = x; // Initialize. while ( n > 1 ) { if ( n & 1 ) // True if last bit of n is 1 (i.e., if n is odd). prod *= power2; power2 *= power2; n >>= 1; // Shift n right 1 bit ( divide n by 2; n /=2 . ). } return prod*=power2; // The final value of n is always 1. } int main() { double x; unsigned int n; cout << "\nEnter the base x: "; cin >> x; cout << "\nEnter the positive integer exponent n: "; cin >> n; cout << "\n\n" << x << " raised to the power " << n << " is " << intPower( x, n ) << "\n\n"; return 0; }