The last digit in an exponentation

J - 52 characters

wd,.10|(^12+12&|)/"1(".@{:`".;._2@,&'x ');._2(1!:1)3

Passes all tests given, though only if the trailing spaces on the third input are removed (I'm guessing this was unintentional).

Solution will work in j602 in console mode (e.g. in terminal, emacs j-shell, etc.). It will not work in j701 (no wd).

Explanation & Mathiness:

The 'magic number' 12 is the LCM of the lengths of the "last digit" tables found in the other answers. All digits repeat with periods 1,2,3 or 4 so they will also repeat with period 12. Adding twelve to that fixes cases where b mod 12 = 0. My solution computes (Last digit of A)^(12+(B mod 12)), giving a number with the same last digit. (I considered a sneaky broken solution eliminating the three characters '12+' by using e.g. B mod 96 where no examples were likely to collide...)


Python 125 107 Chars

O(1) solution

while 1:a,b=map(int,raw_input().split());d=1;exec"d*=a;"*(b%4);c=a%5and d%5;print b/~b+1or c+[0,5][c%2-a%2]

GolfScript 21

~]2/{~.(4%)and?10%n}/

This basically calculate A^C mod 10 where C is in the range [1,4] and C mod 4 = B mod 4, except if B is 0, then C is also 0.

This shortcut is possible because A^(B+4) mod 10 = A^B mod 10 for any non-negative integer A and positive integer B.

Tags:

Math

Code Golf