gpt4 book ai didi

python - 大数(幂)python的最后一位

转载 作者:太空狗 更新时间:2023-10-30 01:44:21 28 4
gpt4 key购买 nike

在 Codewars 上找到这个。该函数接受两个参数 A 和 B,并返回 A^B 的最后一位。下面的代码通过了前两个测试用例,但不会通过下一个测试用例。

def last_digit(n1, n2):
number = n1**n2
if number % 2 == 0:
return number % 10
elif number % 2 != 0:
return number % 10

Test.it("Example tests")
Test.assert_equals(last_digit(4, 1), 4)
Test.assert_equals(last_digit(4, 2), 6)
Test.assert_equals(last_digit(9, 7), 9)
Test.assert_equals(last_digit(10, 10 ** 10), 0)

最佳答案

不要计算n1**n2。当您尝试计算时,问题就来了:

10**(10**10)

这是一个 1 后面跟着一百亿个零。

使用 pow(n1, n2, 10) 这使得问题(更)易于处理,因为它计算幂模 10。然后,由于数字已经以 10 为模减少,该函数可以重写为:

def last_digit(n1, n2):
return pow(n1, n2, 10)

关于python - 大数(幂)python的最后一位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41071646/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com