Problem Link - ModEx Suite in Number theory
Problem Statement:
Given three integers a, b, and m, find a^b mod m.
Approach:
- Your code implements the efficient calculation of a^b mod m using modular exponentiation (also known as “exponentiation by squaring”). This approach is optimal for computing large powers under a modulus.
- See how to calculate modular exponentiation: ModEx Suite in Number theory
Complexity:
- Time Complexity: * The loop in
modexp
runs whileb > 0
, and the number of iterations is proportional to the number of bits inb
. Sinceb
is reduced by half each time (b>>=1
), the number of iterations isO(log b)
- Space Complexity:
O(1)
No extra space needed.