From b7c2008ee951a824fdff738fdc25bfd9542817f1 Mon Sep 17 00:00:00 2001 From: Shri Prakash Bajpai <68155959+Shri2206@users.noreply.github.com> Date: Tue, 13 Oct 2020 19:58:05 +0530 Subject: [PATCH] Add modular_exponentiation --- modular_exponentiation | 44 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 modular_exponentiation diff --git a/modular_exponentiation b/modular_exponentiation new file mode 100644 index 000000000..769542003 --- /dev/null +++ b/modular_exponentiation @@ -0,0 +1,44 @@ +// Iterative C++ program for modular exponentiation. +//The program calculates the value of an integer raised to an integer exponent under modulo an integer. +#include + + +// Iterative Function to calculate a raised to exponent b under modulo c in O(log b) +int power(int a, unsigned int b, int c) +{ + int ans = 1; // Initialize the answer to be returned + + a = a % c; // Update a if it is more than or + // equal to c + + if (a == 0) + { + return 0; // In case a is divisible by c; + } + + while (b > 0) + { + // If b is odd, multiply a with answer + if (b & 1) + { + ans = (ans*a) % c; + } + + // b must be even now + b = b>>1; // b = b/2 + a = (a*a) % c; + } + + return ans; +} + +// Main Function +int main() +{ + int num1 = 2; + int num2 = 5; + int m = 13; + std::cout << "The value of "<