Reputation: 47
I am using Python to find the last digit of a Fibonacci number. This is my code:
import numpy as np
def calc_fib(n):
if n <= 1:
return n
else:
a=np.arange(n+1,dtype='int64')
for i in range(2,n+1):
a[i]=a[i-1]+a[i-2]
return a[n]%10
n = int(input())
print(calc_fib(n))
The code is working fine for small values of n like when n = 10, it yields output of 5, but when using bigger values of n, it yields the output:
/Users/amrsulaiman/Desktop/Algorithms_Coursera/W2_2.py:10: RuntimeWarning: overflow encountered in long_scalars a[i]=a[i-1]+a[i-2]
5
The value 5 is wrong. It is supposed to be 9. How to solve this overflow issue and fix my code.
Upvotes: 3
Views: 3781
Reputation: 34829
One of the properties of decimal addition is that the least-significant digit of the sum only depends on the least-significant digit of the two numbers being added. So you can do all the calculations with only one digit:
def calcFibonacciLastDigit(n):
if n <= 1:
return n
a=0
b=1
for i in range(2,n+1):
c = a+b
if c >= 10: #max value for c is 18
c -= 10 #so subtracting 10 will keep c as one digit
a = b
b = c
return c
print(calcFibonacciLastDigit(331)) #prints 9
Upvotes: 3
Reputation: 1645
The reason you are getting 5 instead of 9 for a n=331
is that you get an overflow as the 93rd fib number as it is bigger than 2^64. So it gets stored as a negative number. The 94th number will also be incorrect as it uses the 93rd which is incorrect, this continues for all number >92.
This can be avoided by using a normal python array, as ints are not bound in python. Give this a try:
def calc_fib(n):
if n <= 1:
return n
else:
a=[0,1]
for i in range(2,n+1):
a.append(a[i-1]+a[i-2])
return a[n]%10
n = int(input())
print(calc_fib(n))
Upvotes: 4