Given three numbers a, b and c, we need to find (ab) % c
Now why do “% c” after exponentiation, because ab will be really large even for relatively small values of a, b and that is a problem because the data type of the language that we try to code the problem, will most probably not let us store such a large number.
Input : a = 2312 b = 3434 c = 6789 Output : 6343 Input : a = -3 b = 5 c = 89 Output : 24
The idea is based on below properties.
(m * n) % p has a very interesting property:
(m * n) % p =((m % p) * (n % p)) % p
if b is even:
(a ^ b) % c = ((a ^ b/2) * (a ^ b/2))%c ? this suggests divide and conquer
if b is odd:
(a ^ b) % c = (a * (a ^( b-1))%c
If we have to return the mod of a negative number x whose absolute value is less than y:
then (x + y) % y will do the trick
Also as the product of (a ^ b/2) * (a ^ b/2) and a * (a ^( b-1) may cause overflow, hence we must be careful about those scenarios
Power is 6
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 (Power in Modular Arithmetic)
- Modular Exponentiation of Complex Numbers
- Matrix Exponentiation
- Find Nth term (A matrix exponentiation example)
- Expected number of moves to reach the end of a board | Matrix Exponentiation
- Modular Division
- Modular Addition
- Modular Arithmetic
- Modular Multiplication
- Modular multiplicative inverse from 1 to n
- Trick for modular division ( (x1 * x2 .... xn) / b ) mod (m)
- Modular multiplicative inverse
- How to avoid overflow in modular multiplication?
- Number of solutions to Modular Equations
- Find modular node in a linked list
- Using Chinese Remainder Theorem to Combine Modular equations
- Recursive Functions
- Recursive Implementation of atoi()
- Recursive Bubble Sort
- Recursive Insertion Sort
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.