binary exponentiation modulo m

To perform binary exponentiation modulo m in C++, you can follow these steps:

  1. Declare three variables: base, exponent, and mod, representing the base number, the exponent, and the modulo value, respectively.

  2. Initialize a variable result as 1. This variable will store the final result.

  3. Use a while loop to iterate until the exponent becomes 0. Inside the loop, perform the following steps:

  4. 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, multiply result by base and take the modulo mod.

  5. Divide the exponent by 2 (right shift operation >>=) to move to the next bit.

  6. Square the base and take the modulo mod.

  7. Repeat steps 4-6 until the exponent becomes 0.

  8. Finally, return the value of result, which will be the binary exponentiation of the base modulo mod.

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.