binary exponentiation
To perform binary exponentiation in C++, you can use the following algorithm:
Step 1: Initialize a variable 'result' to 1. Step 2: Iterate through the bits of the exponent in binary representation from right to left. Step 3: For each bit, perform the following operations: - Multiply 'result' by itself (result = result). - If the current bit is 1, multiply 'result' by the base value (result = base). Step 4: After iterating through all the bits, the final value of 'result' will be the result of exponentiation.
Here is an example to illustrate this algorithm:
#include <iostream>
using namespace std;
// Function to perform binary exponentiation
int binaryExponentiation(int base, int exponent) {
int result = 1;
while (exponent > 0) {
if (exponent & 1) {
result *= base;
}
base *= base;
exponent >>= 1;
}
return result;
}
int main() {
int base = 2;
int exponent = 5;
int result = binaryExponentiation(base, exponent);
cout << base << " raised to the power of " << exponent << " is: " << result << endl;
return 0;
}
In this example, we have a base value of 2 and an exponent value of 5. The binary representation of 5 is 101. Following the algorithm:
- In the first iteration, the result is multiplied by itself (result = 1 * 1 = 1).
- In the second iteration, the result is multiplied by the base value (result = 1 * 2 = 2).
- In the third iteration, the result is multiplied by itself again (result = 2 * 2 = 4).
- After iterating through all the bits, the final value of 'result' is 4, which is the result of 2 raised to the power of 5.