Given a number n, we need to find the last digit of 2n
Input : n = 4
Output : 6
The last digit in 2^4 = 16 is 6
Input : n = 11
Output : 8
The last digit in 2^11 = 2048 is 8
A Naive Solution is to first compute power = pow(2, n), then find the last digit in power using power % 10. This solution is inefficient and also has integer arithmetic issue for slightly large n.
An Efficient Solution is based on the fact that last digits repeat in cycles of 4 if we leave 2^0 which is 1. Powers of 2 (starting from 2^1) are 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, …
We can notice that the last digits are 2, 4, 8, 6, 2, 4, 8, 6, 2, 4, 8, …
1) We compute rem = n % 4. Note that last rem will have value from 0 to 3.
2) We return last digit according to value of remainder.
Remainder Last Digit 1 2 2 4 3 8 0 6
Illustration : Let n = 11, rem = n % 4 = 3. Last digit in 2^3 is 8 which is same as last digit of 2^11.
1 2 4 8 6 2 4 8 6 2 4 8 6 2 4 8 6 2 4 8
Time Complexity: O(1)
Auxiliary Space: O(1)
Can we generalize it for any input numbers? Please refer Find Last Digit of a^b for Large Numbers
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.
- K-th digit in 'a' raised to power 'b'
- Find unit digit of x raised to power y
- Find last five digits of a given five digit number raised to power five
- Smallest N digit number which is a perfect fourth power
- 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
- Min steps to convert N-digit prime number into another by replacing a digit in each step
- Count of Numbers in Range where first digit is equal to last digit of the number
- Find the remainder when First digit of a number is divided by its Last digit
- Count numbers in a range with digit sum divisible by K having first and last digit different
- Count of pairs (A, B) in range 1 to N such that last digit of A is equal to the first digit of B
- Largest number less than N with digit sum greater than the digit sum of N
- Count 'd' digit positive integers with 0 as a digit
- Last digit of a number raised to last digit of N factorial
- Count n digit numbers not having a particular digit
- Check if frequency of each digit is less than the digit
- Larger of a^b or b^a (a raised to power b or b raised to power a)
- Power Set
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.