简体   繁体   中英

I get the error “RuntimeWarning: overflow encountered in long_scalars” when trying to calculate the last digit of a Fibonacci number using python

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.

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))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM