Search code examples
pythonlargenumber

Last digit of huge number Python


I am trying to solve

x1 ^ (x2 ^ (x3 ^ (... ^ xn)))

where x1, x2, etc are numbers in the give list(lst) and the function should return last digit of result.

For example, if lst = [3, 4, 5], it should return 1.
Another example, if lst = [499942, 898102, 846073], it should return 6.

My code has passed sucessfully in the test with over 600 random lists from smallest to I think up to 6 digits long, but failed on these two lists:

[2, 2, 101, 2], [12, 30, 21]

Function:

def last_digit(lst):
    result = 1
    for num in reversed(lst):
        result = pow(num, result, 100)
    print(lst)
    return result%10

Solution

  • You're on the right track it can word for many cases but there's a small problem. see you are trying to calculate the last digit of a sequence of exponentiations. The problem is in how you're reducing intermediate results; You're currently reducing each intermediate result modulo 100, which might not always give you the correct last digit.

    Here, you need to reduce each intermediate result modulo 10 instead of 100. Here's the modified version:

    def last_digit(lst):
        if not lst:
            return 1  
        # Handle the case when the list is empty
        result = 1
        for num in reversed(lst):
            result = num ** (result if result < 4 else result % 4 + 4)
            # Reduce result modulo 4 and add 4 for optimization
        return result % 10
    

    See in the loop firstly, we calculating the result modulo 4 for optimisation purposes and add 4. This step ensures that we are always working with positive exponents, which simplifies the calculation. Finally, we take the result modulo 10 to get the last digit.

    It should handle your test cases correctly, including those that previously failed. Let me know if you need any other help.