I need to find the unit digit of x1 ^ (x2 ^ (x3 ^ (... ^ xn)))
from integers passed into the function as a list.
For example the input [3, 4, 2]
would return 1
because 3 ^ (4 ^ 2) = 3 ^ 16 = 43046721
the last digit of which is 1.
The function needs to be efficient as possible because obviously trying to calculate 767456 ^ 981242
is not very quick.
I have tried a few methods but I think the best way to solve this is using sequences. For example any number ending in a 1
, when raised to a power, will always end in 1
. For 2
, the resulting number will end in either 2, 4, 6 or 8
.
If a number is raised to a power, the last digit of the resulting number will follow a pattern based on the last digit of the exponent:
1: Sequence is 1
2: Sequence is 2, 4, 8, 6
3: Sequence is 3, 9, 7, 1
4: Sequence is 4, 6
5: Sequence is 5
6: Sequence is 6
7: Sequence is 7, 9, 3, 1
8: Sequence is 8, 4, 2, 6
9: Sequence is 9, 1
0: Sequence is 0
I think the easiest way to calculate the overall last digit is to work backwards through the list and calculate the last digit of each calculation one at a time until I get back to the start but I am not sure how to do this? If anyone could help or suggest another method that is equally or more efficient than that would be appreciated.
I have this code so far but it does not work for very large numbers
def last_digit(lst):
if lst == []:
return 1
total = lst[len(lst)-2] ** lst[len(lst)-1]
for n in reversed(range(len(lst)-2)):
total = pow(lst[n], total)
return total%10
Edit: 0 ^ 0
should be assumed to be 1