<s>[INST] What is the best algorithm for finding the last digit of an enormous exponent? I found most answers here not clear enough for my case such as
$$
123155131514315^{4515131323164343214547}
$$
I wrote the $n\bmod10$ in Python and execution time ran out. So I need a faster algorithm or method. Sometimes, the result is incorrect as it failed the test case.
 [/INST] If $a=10q+b$, then $a^n \equiv b^n \bmod 10$, and so it suffices to consider $b^n$, for $b = 0, 1, \dots, 9$.
These powers repeat as follows:
$0^n = 0, 0, \dots $
$1^n = 1, 1, \dots $
$2^n = 2, 4, 8, 6, 2, 4, 8, 6, \dots $
$3^n = 3, 9, 7, 1, 3, 9, 7, 1, \dots $
$4^n = 4, 6, 4, 6, \dots $
$5^n = 5, 5, \dots $
$6^n = 6, 6, \dots $
$7^n = 7, 9, 3, 1, 7, 9, 3, 1,\dots $
$8^n = 8, 4, 2, 6, 8, 4, 2, 6, \dots $
$9^n = 9, 1, 9, 1, \dots $
So, you only have to compute $n \bmod m$, where $m$ is the period corresponding to $b$, and look up the answer in the list above.
</s>