![]() |
VOOZH | about |
Given three integers x, n, and M, compute (xn) % M (remainder when x raised to the power n is divided by M).
Examples :
Input: x = 3, n = 2, M = 4
Output: 1
Explanation: 32 % 4 = 9 % 4 = 1.Input: x = 2, n = 6, M = 10
Output: 4
Explanation: 26 % 10 = 64 % 10 = 4.
Table of Content
We initialize the result as 1 and iterate from 1 to n, updating the result by multiplying it with x and taking the modulo by M in each step to keep the number within integer bounds.
1
The idea of binary exponentiation is to reduce the exponent by half at each step, using squaring, which lowers the time complexity from O(n) to O(log n).
-> xn = (xn/2)2 if n is even.
-> xn = x*xn-1 if n is odd.
Step by step approach:
n is greater than 0.1