For a given list [x1, x2, x3, ..., xn]
compute the last (decimal) digit of x1 ^ (x2 ^ (x3 ^ (... ^ xn)))
.
E. g.,
last_digit([3, 4, 2]) == 1
because 3 ^ (4 ^ 2) = 3 ^ 16 = 43046721
.
Beware: Powers grow incredibly fast. For example, 9 ^ (9 ^ 9)
has more than 369 million of digits. lastDigit
has to deal with such numbers efficiently.
Corner cases: We assume that 0 ^ 0 = 1
and that lastDigit
of an empty list equals to 1.
This challenge comes from Bodigrim on CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (4)
Javascript:
can we have some explain please ?
Yes.
Let's look at a spreadsheet of xy % 10.
For x, the values repeat every 10, that is, xy % 10 == (x+10)y % 10.
For y, the values repeat every 4, that is, xy % 10 == xy+4 % 10, except for the case y=0.
Why is it so? I don't know, maybe someone else can explain/prove the math. All I know is that I can use it to make the power calculations much smaller. If I need the last digit of 345435456, I calculate instead the last digit of (345435%10)(456-1%4+1)=53=125, which is 5.
So that's what I'm doing in the function, extracting the last two numbers out of the array, calculating the right-most digit of their power and pushing it back. I also handle the case of empty list as per the requirements, not sure why they wanted it to be 1.
Javascript
Not sure how to get the last digit from more than 369 million of digits, so handled it with 0 and empty list as 1.