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 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Larger of a^b or b^a (a raised to power b or b raised to power a)
- Find last five digits of a given five digit number raised to power five
- Find the sum of power of bit count raised to the power B
- Last digit of a number raised to last digit of N factorial
- Number of digits in 2 raised to power n
- Check if a number can be expressed as x^y (x raised to power y)
- Find multiple of x closest to or a ^ b (a raised to power b)
- Find unit digit of x raised to power y
- K-th digit in 'a' raised to power 'b'
- Find value of y mod (2 raised to power x)
- GCD of a number raised to some power and another number
- Minimum removals in a number to be divisible by 10 power raised to K
- Sum of absolute difference of all pairs raised to power K
- Find the first and last M digits from K-th power of N
- Sum of each element raised to (prime-1) % prime
- Numbers of Length N having digits A and B and whose sum of digits contain only digits A and B
- Minimum digits to be removed to make either all digits or alternating digits same
- Find power of power under mod of a prime
- Check if given number is a power of d where d is a power of 2
- Compute power of power k times % m