I need to find the last digit of large power. When I get simple x^n, I solve problem with this: pow(x, n, 10). But what should I do when I have such example: 103171^(14394^(221515^(441792^507709)))? I noticed the cyclicity of specific digits, but it's not enough. I am afraid I'm missing some important point. As an input of my main function last_digit I get list of numbers (lst), let's say [3, 4, 2]- this means I need to compute 3 ^ (4 ^ 2). I've got about 630 tests to pass and I can only make about 580 (most of them are randomly generated). Here's my code I've tried:
CYCLES = {
0 : [0, 0, 0, 0],
1 : [1, 1, 1, 1],
2 : [2, 4, 8, 6],
3 : [3, 9, 7, 1],
4 : [4, 6, 4, 6],
5 : [5, 5, 5, 5],
6 : [6, 6, 6, 6],
7 : [7, 9, 3, 1],
8 : [8, 4, 2, 6],
9 : [9, 1, 9, 1]
}
def power_rec(lst):
remainder = pow(lst[-2], lst[-1], 4)
if len(lst) == 2:
first_num = int(str(lst[0])[-1])
second_num = int(str(lst[1])[-1])
return CYCLES[first_num][second_num - 1]
lst = lst[:-2] + [ remainder ]
return power_rec(lst)
def last_digit(lst):
if len(lst) == 2:
return pow(lst[0], lst[1], 10)
if lst == []:
return 1
if len(lst) == 1:
return int(str(lst[0])[-1])
return power_rec(lst)
E.g. I cannot pass tests with inputs: [555913, 845991, 261716, 431426, 571315, 456986, 461380, 413475] or [2, 2, 101, 2].
I have to assume that 0 ^ 0 = 1 and that last_digit of an empty list equals to 1. I'd appreciate any helpful tips.
UPDATE. Found shortest solution:
def last_digit(lst):
result = 1
for num in lst[::-1]:
result = pow(num, (result if result < 4 else result % 4 + 4) )
return result % 10