I am trying to find the last digit of sum of Fibonacci Series. I calculate the sum as F(n+2) - 1
. The below code is working fine but it is slow for large numbers (e.g 99999
).
How can I optimize this?
n = int(input())def last_digit(n):a, b = 0, 1for i in range(n+2):a, b = b, a + breturn (a-1) % 10print(last_digit(n))
Look at this table: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html
notice that fib(60)
last digit is 0
and fib(61)
last digit is 1
, that is same as fib(0)
and fib(1)
, thus starting at 60
last digits starts to repeat, so you can calculate last digit for fib(n%60)
rather than fib(n)
.
For example last digit is same for fib(115)
and fib(55)
and equal to 5
.