Given three numbers x, y and p, compute (xy) % p.
Input: x = 2, y = 3, p = 5 Output: 3 Explanation: 2^3 % 5 = 8 % 5 = 3. Input: x = 2, y = 5, p = 13 Output: 6 Explanation: 2^5 % 13 = 32 % 13 = 6.
Below is discussed iterative solution.
The problem with above solutions is, overflow may occur for large value of n or x. Therefore, power is generally evaluated under modulo of a large number.
Below is the fundamental modular property that is used for efficiently computing power under modular arithmetic.
(ab) mod p = ( (a mod p) (b mod p) ) mod p For example a = 50, b = 100, p = 13 50 mod 13 = 11 100 mod 13 = 9 (50 * 100) mod 13 = ( (50 mod 13) * (100 mod 13) ) mod 13 or (5000) mod 13 = ( 11 * 9 ) mod 13 or 8 = 8
Below is the implementation based on above property.
Power is 6
Time Complexity of above solution is O(Log y).
Modular exponentiation (Recursive)
This article is contributed by Shivam Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Modular exponentiation (Recursive)
- Modular Exponentiation of Complex Numbers
- Modular Arithmetic
- Modular Addition
- Modular Multiplication
- Modular Division
- Modular multiplicative inverse
- Modular multiplicative inverse from 1 to n
- Trick for modular division ( (x1 * x2 .... xn) / b ) mod (m)
- Number of solutions to Modular Equations
- How to avoid overflow in modular multiplication?
- Find modular node in a linked list
- Using Chinese Remainder Theorem to Combine Modular equations
- Matrix Exponentiation
- Find Nth term (A matrix exponentiation example)
- Expected number of moves to reach the end of a board | Matrix Exponentiation
- Find the sum of power of bit count raised to the power B
- Find power of power under mod of a prime
- Compute power of power k times % m
- Check if given number is a power of d where d is a power of 2