CodeWars里的5kyu题目Last digit of a leage number
题目说明:
Description:
Define a function that takes in two non-negative integers aaa and bbb and returns the last decimal digit of aba^ba
b
. Note that aaa and bbb may be very large!
For example, the last decimal digit of 979^79
7
is 999, since 97=47829699^7 = 47829699
7
=4782969. The last decimal digit of (2200)2300({2{200}}){2^{300}}(2
200
)
2
300
, which has over 109210^{92}10
92
decimal digits, is 666. Also, please take 000^00
0
to be 111.
You may assume that the input will always be valid.
Examples
last_digit(4, 1) # returns 4
last_digit(4, 2) # returns 6
last_digit(9, 7) # returns 9
last_digit(10, 10 ** 10) # returns 0
last_digit(2 ** 200, 2 ** 300) # returns 6
Remarks
JavaScript, C++, R, PureScript
Since these languages don’t have native arbitrarily large integers, your arguments are going to be strings representing non-negative integers instead.
Python解决办法:
为了避免时间超限,将0-9数字分为三组,分别是1、4、2次循环得到原先数字,将n1去10的余数,将n2去对应循环次数的余数,进行简化计算。
def last_digit(n1, n2):
l1 = [0, 1, 5, 6]
l2 = [2, 3, 7, 8]
l3 = [4, 9]
n1 = n1 % 10
if n2 == 0:
return 1
if n1 in l1:
return n1
elif n1 in l2:
n2 = n2 % 4
if n2 == 0:
m = (n1 ** 4) % 10
return m
else:
m = (n1 ** n2) % 10
return m
elif n1 in l3:
n2 = n2 %2
if n2 ==0:
m = (n1 ** 2) % 10
return m
else:
m = (n1 ** n2) % 10
return m