If you raise any number to the fifth power, the last digit doesn’t change.
Here’s a little Python code to verify this claim.
>>> [n**5 for n in range(10)] [0, 1, 32, 243, 1024, 3125, 7776, 16807, 32768, 59049]
In case you’re not familiar with Python, or familiar with Python but not familiar with list comprehensions, the code is very similar to set builder notation in math:
{n5 | n = 0, 1, 2, … 9}
To emphasize the last digits, we could take the remainder by 10:
>>> [n**5 % 10 for n in range(10)] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The reason this works is related to Fermat’s little theorem.
We could generalize this to the last digits in other bases. For example, in base 21, raising numbers to the 13th power doesn’t change the last digit. You could verify this by running
[x**13 % 21 for x in range(21)]
Why do we take 5th powers in base 10 and 13th powers in base 21? Because φ(10) + 1 = 5 and φ(21) + 1 = 13 where φ(m) is Euler’s “totient” function applied to the base. The function φ(m) is defined as the number of positive integers less than m that are relatively prime to m.
If we’re in base 30, φ(30) = 8, and so we’d expect 9th powers to leave the last digit unchanged. And we can evaluate
[n**9 % 30 for n in range(30)]
to see that this is the case.
Now let’s try base 16. We have φ(16) = 8, so let’s raise everything to the 9th power.
>>> [n**9 % 16 for n in range(16)] [0, 1, 0, 3, 0, 5, 0, 7, 0, 9, 0, 11, 0, 13, 0, 15]
That didn’t work out the way the other examples did. Why’s that? The bases 10, 21, and 30 are the product of distinct primes, but 16 is a prime power.
However, there’s something else interesting going on in base 16. Instead of taking the remainder by 16, i.e. looking at the last hexadecimal digit, let’s look at all the digits.
>>> [hex(n**9) for n in range(16)] ['0x0', '0x1', '0x200', '0x4ce3', '0x40000', ..., '0x8f3671c8f']
In base 16, the last digit of n9 is not the same as the last digit of n. But the last non-zero digit is the same as the last digit of n.
You don’t actually need the full totient; what you need is LCM({φ(p^i) | p^i is maximal prime power divisor of n}).
For base 21, this says that x -> x^7 is the identity function of Z/21