modular exponentiation algorithm c++
Here is an explanation of the modular exponentiation algorithm in C++:
Input: The algorithm takes three parameters:
base
,exponent
, andmodulus
. Thebase
represents the number to be raised to the power of theexponent
, and themodulus
is the number by which the result is to be divided.Initialize: Create a variable
result
and set it to 1. This variable will store the final result of the modular exponentiation calculation.Loop: Start a loop that iterates
exponent
number of times.Condition: Check if the least significant bit of the
exponent
is set or not. This can be done by performing a bitwise AND operation (exponent & 1
). If the result is 1, it means the bit is set.Update
result
: If the condition is true, multiplyresult
withbase
modulomodulus
and store the result back inresult
. This step is performed to keep the result within the range of the modulus.Update
base
: Square the value ofbase
and store the result back inbase
. This step is performed to efficiently calculate the next power ofbase
.Update
exponent
: Right-shift the value ofexponent
by 1 bit. This step effectively divides theexponent
by 2.Repeat: Go back to step 4 and continue the loop until the
exponent
becomes 0.Output: The final value of
result
is the modular exponentiation of thebase
raised to the power of theexponent
modulomodulus
.
Here is an example implementation of the modular exponentiation algorithm in C++:
int modularExponentiation(int base, int exponent, int modulus) {
int result = 1;
while (exponent > 0) {
if (exponent & 1) {
result = (result * base) % modulus;
}
base = (base * base) % modulus;
exponent >>= 1;
}
return result;
}
You can use this function by passing the appropriate values for base
, exponent
, and modulus
. The function will return the modular exponentiation result.