binary exponentiation modulo m
To perform binary exponentiation modulo m in C++, you can follow these steps:
Declare three variables:
base
,exponent
, andmod
, representing the base number, the exponent, and the modulo value, respectively.Initialize a variable
result
as 1. This variable will store the final result.Use a while loop to iterate until the exponent becomes 0. Inside the loop, perform the following steps:
Check if the least significant bit of the exponent is set (i.e., it is equal to 1). You can do this by using the bitwise AND operator (
&
). If the bit is set, multiplyresult
bybase
and take the modulomod
.Divide the exponent by 2 (right shift operation
>>=
) to move to the next bit.Square the
base
and take the modulomod
.Repeat steps 4-6 until the exponent becomes 0.
Finally, return the value of
result
, which will be the binary exponentiation of thebase
modulomod
.
Here is an example of a C++ function that performs binary exponentiation modulo m:
#include <iostream>
int binaryExponentiationModulo(int base, int exponent, int mod) {
int result = 1;
while (exponent > 0) {
if (exponent & 1)
result = (result * base) % mod;
base = (base * base) % mod;
exponent >>= 1;
}
return result;
}
int main() {
int base = 2;
int exponent = 10;
int mod = 1000000007;
int result = binaryExponentiationModulo(base, exponent, mod);
std::cout << "Result: " << result << std::endl;
return 0;
}
In this example, the function binaryExponentiationModulo
takes three arguments: base
, exponent
, and mod
. It calculates the binary exponentiation of base
modulo mod
using the steps mentioned above. Finally, the result is printed to the console.