【Codewars python 5kyu】:Last digit of a large number

  • Post author:
  • Post category:python


问题描述:

Define a function that takes in two non-negative integers

a

and

b

and returns the last decimal digit of

a^b

. Note that

a

and

b

may be very large!

For example, the last decimal digit of

9^7

is

9

, since

9^7 = 4782969

. The last decimal digit of

(2^200)^(2^300)

, which has over

10^92

decimal digits, is

6

. Also, please take

0^0

to be

1

.

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.

代码实现:

#codewars第二十七题
def last_digit(n1, n2):   # ( 最蠢的做法 )
    list2 = [2, 4, 8, 6]
    list3 = [3, 9, 7, 1]
    list4 = [4, 6]
    list7 = [7, 9, 3, 1]
    list8 = [8, 4, 2, 6]
    list9 = [9, 1]
    
    if n2 == 0: return 1
    if n1 == 0: return 0
    str1 = str(n1) 
    num = int(str1[-1])
    if num == 0: return 0
    if num == 1: return 1
    elif num == 5: return 5
    elif num == 6: return 6
    elif num == 2:
        num2 = n2 % 4 - 1
        return list2[num2]
    elif num == 3:
        num3 = n2 % 4 - 1
        return list3[num3]
    elif num == 4:
        num4 = n2 % 2 - 1
        return list4[num4]
    elif num == 7:
        num7 = n2 % 4 - 1
        return list7[num7]
    elif num == 8:
        num8 = n2 % 4 - 1
        return list8[num8]
    else:
        num9 = n2 %2 - 1 
        return list9[num9]

# 另解一 (这就是熟悉方法的好处!!!)
def last_digit(n1, n2):
    return pow( n1, n2, 10 )  #pow(x, y, z)函数是计算x的y次方,如果z在存在,则再对结果进行取模,其结果等效于pow(x,y)%z

# 另解二(我的结果的简化版)
rules = {
    0: [0,0,0,0],   
    1: [1,1,1,1],
    2: [2,4,8,6],
    3: [3,9,7,1],
    4: [4,6,4,6], 
    5: [5,5,5,5], 
    6: [6,6,6,6], 
    7: [7,9,3,1], 
    8: [8,4,2,6], 
    9: [9,1,9,1],
}
def last_digit(n1, n2):
    ruler = rules[int(str(n1)[-1])]
    return 1 if n2 == 0 else ruler[(n2 % 4) - 1]

# 另解三(没有二简化  还是走了不少弯路)
def last_digit(n1, n2):
    last_dict = {
        0: [0],
        1: [1], 
        2: [2, 4, 6, 8],
        3: [3, 9, 7, 1],
        4: [4, 6],
        5: [5],
        6: [6],
        7: [7, 9, 3, 1],
        8: [8, 4, 2, 6],
        9: [9, 1]}
        
    if n2 == 0:
        return 1
    a = n1 % 10
    return last_dict[a][(n2-1)%len(last_dict[a])]

last_digit(123232,140249)



版权声明:本文为qq_36362028原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。