Given three numbers a, b and c such that a, b and c can be at most 1016. The task is to compute (a*b)%c
A simple solution of doing ( (a % c) * (b % c) ) % c would not work here. The problem here is that a and b can be large so when we calculate (a % c) * (b % c), it goes beyond the range that long long int can hold, hence overflow occurs. For example, If a = (1012+7), b = (1013+5), c = (1015+3).
Now long long int can hold upto 4 x 1018(approximately) and a*b is much larger than that.
Instead of doing direct multiplication we can add find a + a + ……….(b times) and take modulus with c each time we add a so that overflow don’t take place. But this would be inefficient looking at constraint on a, b and c. We have to somehow calculate (∑ a) % c in optimized manner.
We can use divide and conquer to calculate it. The main idea is:
- If b is even then a*b = (2*a) * (b/2)
- If b is odd then a*b = a + (2*a)*((b-1)/2)
Below is the implementation of the algorithm:
See this for sample run.
Time Complexity: O(log b)
This article is contributed by Madhur Modi. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Compute n! under modulo p
- How to compute mod of a big number?
- Compute nCr % p | Set 3 (Using Fermat Little Theorem)
- Compute sum of digits in all numbers from 1 to n
- Compute nCr % p | Set 2 (Lucas Theorem)
- Compute the maximum power with a given condition
- Compute the parity of a number using XOR and table look-up
- Efficient Program to Compute Sum of Series 1/1! + 1/2! + 1/3! + 1/4! + .. + 1/n!
- Compute average of two numbers without overflow
- Compute maximum of the function efficiently over all sub-arrays
- Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)
- Program to compute division upto n decimal places
- Compute power of power k times % m
- Sum of all i such that (2^i + 1) % 3 = 0 where i is in range [1, n]
- GCD of elements in a given range