Given positive integers k, a and b we need to print last k digits of a^b ie.. pow(a, b).
Input Constraint: k <= 9, a <= 10^6, b<= 10^6
Input : a = 11, b = 3, k = 2 Output : 31 Explanation : a^b = 11^3 = 1331, hence last two digits are 31 Input : a = 10, b = 10000, k = 5 Output : 00000 Explanation : a^b = 1000..........0 (total zeros = 10000), hence last 5 digits are 00000
First Calculate a^b, then take last k digits by taking modulo with 10^k. Above solution fails when a^b is too large, as we can hold at most 2^64 -1 in C/C++.
The efficient way is to keep only k digits after every multiplication. This idea is very simiar to discussed in Modular Exponentiation where we discussed a general way to find (a^b)%c, here in this case c is 10^k.
Here is implementation.
Last 2 digits of 11^3 = 31
Time Complexity : O(log b)
Space Complexity : O(1)
This article is contributed by Pratik Chhajer. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
- Number of digits in 2 raised to power n
- Find last five digits of a given five digit number raised to power five
- Larger of a^b or b^a (a raised to power b or b raised to power a)
- Find value of y mod (2 raised to power x)
- K-th digit in 'a' raised to power 'b'
- Find multiple of x closest to or a ^ b (a raised to power b)
- Check if a number can be expressed as x^y (x raised to power y)
- Find unit digit of x raised to power y
- Minimum removals in a number to be divisible by 10 power raised to K
- GCD of a number raised to some power and another number
- Sum of digits of a given number to a given power
- Number of digits in N factorial to the power N
- Print numbers with digits 0 and 1 only such that their sum is N
- Print first k digits of 1/n where n is a positive integer
- Print all possible words from phone digits