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:
- Include necessary libraries and declare the standard namespace.
- Define the
moduloExponentiation
function, which takes three parameters:base
,exponent
, andmodulo
. It will return the result of(base^exponent) % modulo
. - Initialize a variable
result
to 1, which will store the final result. - Use a
while
loop to iterate whileexponent
is greater than 0. - Inside the loop, check if
exponent
is odd (i.e.,exponent % 2 == 1
). If it is, updateresult
by multiplying it withbase
and taking the modulus ofmodulo
. - Update
base
by squaring it and taking the modulus ofmodulo
. - Halve the value of
exponent
(integer division by 2) in each iteration of the loop. - Continue the loop until
exponent
becomes 0. Return the final value of
result
, which is the result of(base^exponent) % modulo
.In the
main
function, input the values ofbase
,exponent
, andmodulo
from the user.- Call the
moduloExponentiation
function with these values and store the result. - Display the result to the user.