Modulo Exponentiaon,Iteratve Modulo Exponentiation

#include <iostream>

using namespace std;

// Function to calculate (base^exponent) % modulo using iterative exponentiation
long long moduloExponentiation(long long base, long long exponent, long long modulo) {
    long long result = 1;
    while (exponent > 0) {
        if (exponent % 2 == 1) {
            result = (result * base) % modulo;
        }
        base = (base * base) % modulo;
        exponent /= 2;
    }
    return result;
}

int main() {
    long long base, exponent, modulo;
    cout << "Enter base: ";
    cin >> base;
    cout << "Enter exponent: ";
    cin >> exponent;
    cout << "Enter modulo: ";
    cin >> modulo;

    long long result = moduloExponentiation(base, exponent, modulo);
    cout << "Result: " << result << endl;

    return 0;
}

This C++ code defines a function called moduloExponentiation for calculating (base^exponent) % modulo using iterative exponentiation. Here's an explanation of each step:

  1. Include necessary libraries and declare the standard namespace.
  2. Define the moduloExponentiation function, which takes three parameters: base, exponent, and modulo. It will return the result of (base^exponent) % modulo.
  3. Initialize a variable result to 1, which will store the final result.
  4. Use a while loop to iterate while exponent is greater than 0.
  5. Inside the loop, check if exponent is odd (i.e., exponent % 2 == 1). If it is, update result by multiplying it with base and taking the modulus of modulo.
  6. Update base by squaring it and taking the modulus of modulo.
  7. Halve the value of exponent (integer division by 2) in each iteration of the loop.
  8. Continue the loop until exponent becomes 0.
  9. Return the final value of result, which is the result of (base^exponent) % modulo.

  10. In the main function, input the values of base, exponent, and modulo from the user.

  11. Call the moduloExponentiation function with these values and store the result.
  12. Display the result to the user.