Python计算斐波那契数末位遇RuntimeWarning溢出错误,如何修复?
The problem here is that even with int64 (which can hold up to ~9e18), Fibonacci numbers grow exponentially—they’ll quickly exceed the maximum value of int64, causing integer overflow. When this happens, the intermediate values in your numpy array become corrupted, leading to an incorrect final modulo result.
The Simple Fix: Modulo at Every Step
Since we only care about the last digit of the Fibonacci number, we can leverage a key property of modular arithmetic:(a + b) % 10 = [(a % 10) + (b % 10)] % 10
This means we don’t need to store the full Fibonacci number—just its last digit at each step. This keeps all values between 0 and 9, eliminating overflow entirely. We also don’t need numpy for this; plain Python variables work much more efficiently here.
Here’s the revised code:
def calc_fib_last_digit(n): if n <= 1: return n # Track only the last digits of the two previous Fibonacci numbers prev_prev = 0 # F(0) prev = 1 # F(1) for _ in range(2, n + 1): # Calculate current last digit and update pointers current = (prev_prev + prev) % 10 prev_prev, prev = prev, current return prev n = int(input()) print(calc_fib_last_digit(n))
Why This Works
- We never deal with numbers larger than 18 (since 9 + 9 = 18), so overflow is impossible.
- The algorithm runs in O(n) time with O(1) space—way more efficient than storing an entire numpy array, especially for large n.
Bonus Optimization: Pisano Period
For extremely large n (like 1e6 or bigger), you can use the Pisano period for modulo 10, which is 60. This means the last digits of Fibonacci numbers repeat every 60 terms. So you can reduce n to n % 60 first—this cuts down the number of iterations drastically:
def calc_fib_last_digit(n): # Reduce n using Pisano period for mod 10 n = n % 60 if n <= 1: return n prev_prev = 0 prev = 1 for _ in range(2, n + 1): current = (prev_prev + prev) % 10 prev_prev, prev = prev, current return prev
This version will handle any n, no matter how large, in at most 60 iterations.
内容的提问来源于stack exchange,提问作者Amr Gaballah

