Home > Mobile >  Algorithm which finds the last digit of raising to a power every previous digit into the current
Algorithm which finds the last digit of raising to a power every previous digit into the current

Time:08-25

I've been trying to implement the algorithm which does raising to a power every previous digit to current digit, which is also raised to. Then I find the last digit of this number. Here is the formula of this algorithm:

(x0 ** (x1 ** (x2 ** (x3 ** (...) **(Xn))))))

Then I find the last digit like that:

return find_last_digit % 10

If the list is empty, programm must return 1. I have the Solution of this problem:

def last_digit(lst):
    if len(lst) > 0:
        temp = lst[-1]
        for i in range(len(lst) - 2, -1, -1):
            temp = lst[i] ** temp
        return temp % 10
    else:
        return 1

But as you can see, this code takes a lot of time to be implemented if any value of the input list is large. Could you answer me, how can I make this code more effecient? Thx a lot

CodePudding user response:

Here are some observations that can make the calculations more efficient:

  • As we need the last digit, and we are essentially doing multiplications, we can use the rules of modular arithmetic. If

  • Related