You are given two integers a and b in the form of strings. You need to find the last digit of a^b (ab).
Examples:
Input: a = "3", b = "10"
Output: 9
Explanation: 310 = 59049. The last digit is 9.
Input: a = "6", b = "2"
Output: 6
Explanation: 62 = 36. The last digit is 6.
Using Cyclicity of Last Digit (Mod 10) - O(n) Time O(1) Space
The last digit of powers follows a repeating cycle (maximum length = 4). Instead of computing large powers, we reduce the exponent using modulo 4 and use only the last digit of the base.
Here are few examples numbers and last digits of their powers
- 1: 1, 1, 1, 1, 1, 1, .... [Cycle Length is 1]
- 2: 4, 8, 6, 2, 4, 8, 6, 2,... [Cycle Length is 4]
- 3: 9, 7, 1, 3, 9, 7, 1, 3,... [Cycle Length is 4]
- 4: 6, 4, 6, 4, 6, 4, 6, 4, ...... [Cycle Length is 2]
- 5: 5, 5, 5, 5, 5, ... [Cycle Length is 1]
- 6: 6, 6, 6, 6, 6...... [Cycle Length is 1]
- 7: 9, 3, 1, 7, 9, 3, 1, 7,...... [Cycle Length is 4]
- 8: 4, 2, 6, 8, 4, 2, 6, 8, ..... [Cycle Length is 4]
- 9: 1, 9, 1, 9, 1, 9...... [Cycle Length is 2]
Algorithm:
- Extract the last digit of base a.
- Compute b % 4 using string-based modulo (since b is large).
- If b % 4 == 0, take the exponent as 4, otherwise b % 4.
- Compute power using reduced exponent.
- Return the last digit of the result (% 10).
Why does this work?
- Any number’s last digit depends o (a^b) mod 10. The possible last digits are 0–9. When you keep multiplying, results must eventually repeat (finite possibilities)
- If the base 'a' is coprime with 10 (i.e., last digit is 1, 3, 7, or 9), then (a^4) mod 10 is 1. After every 4 powers, the pattern resets. so last digits repeat every 4.
- If the base is not coprime with 10 (i.e., last digit is 2, 4, 5, 6 or 8), then we can find the pattern case by case basis as there are finite possibilities. For example for 2, 5 or 6, it is always the same digit.
Time Complexity:O(n)
Space Complexity:O(1)