我的代码如下:
m, n = map(int, input().split())
# write function "fibtotal" which takes input x and gives accurate fib(x+2)%10 (as sum till fib(x) == fib(x+2) - 1)
# using above function get fibtotal(m-1) and fibtotal(n)
# subtract fibtotal(m-1) from fibtotal(n) and do mod 10 gives last digit of sum from m to n
# take care of handling large input sizes, 0 ≤ ≤ ≤ 10^14
def fibtotal(x):
sum = 1 # if both initial conditions fail then loop starts from 2
x= x % 60 # pisano period of 10 is 60 and to get last digit we need to divide by 10
if x == 0:
sum = 1 # fib(2)
return sum
if x == 1:
sum = 2 # fib(3)
return sum
a, b = 0, 1
for i in range(2, x+3): # to find sum till fib(x+2)
c = (a+b)%10
sum += c
a, b = b%10, c%10
return sum%10
# no need to subtract 1 from both as they cancel out
print(fibtotal(n)-fibtotal(m-1))
以下案例使用此算法失败:
10 10
我的输出:4,正确的输出:5
10 200
我的输出:5,正确的输出:2
1234 12345
我的输出:2,正确的输出:8
(可能还有更多)
我想知道问题出在哪里以及如何解决?有没有更好的方法使用相同的基本原理?