You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求斐波那契数列和的最后一位:优化大输入下的Python代码

Optimizing Fibonacci Sum Last Digit Calculation for Large n

Hey there! I see your current code works fine for small inputs, but struggles with large values like 613455 because it loops all the way up to n. Let's fix that with some mathematical shortcuts to make the calculation constant-time, no matter how big n gets.

The Key Insights

First, let's break down two critical math facts that will supercharge our solution:

  1. Fibonacci Sum Formula: The sum of the first n Fibonacci numbers (where F(0)=0, F(1)=1) equals F(n+2) - 1. Instead of adding up every term, we just need to compute F(n+2), subtract 1, then take the last digit (mod 10).
  2. Pisano Period: Fibonacci numbers modulo m repeat in a cycle called the Pisano period. For m=10 (since we care about the last digit), this period is 60. That means F(k) mod 10 = F(k + 60) mod 10 for any k. So we never need to compute Fibonacci numbers beyond the 60th term—we just find where n+2 falls in this cycle.

The Optimized Code

Here's the revised implementation that leverages these facts:

def fibonacci_sum_last_digit(n):
    if n < 2:
        return n  # S(0)=0, S(1)=1, last digit is the number itself
    
    # Use the sum formula: S(n) = F(n+2) - 1
    target = n + 2
    pisano_period = 60  # Period for mod 10
    
    # Find the position within the Pisano cycle
    remainder = target % pisano_period
    
    # If remainder is 0, target is a multiple of 60—F(60) mod10 is 0
    if remainder == 0:
        return 9  # (0 - 1) mod10 = 9
    
    # Compute F(remainder) mod10
    a, b = 0, 1
    for _ in range(2, remainder + 1):
        a, b = b, (a + b) % 10
    
    # Calculate (F(remainder) -1) mod10 to get the last digit of the sum
    return (b - 1) % 10

n = int(input())
print(fibonacci_sum_last_digit(n))

Why This Works

  • No More Long Loops: Even for n=613455, we only loop up to 17 times (since 613455+2=613457, 613457 mod60=17) instead of 613k times. That's a massive speedup!
  • Correctness: The Pisano period ensures we get the same mod10 result as computing the actual large Fibonacci number, and the sum formula eliminates the need to add every term.

Quick Test Cases

Let's verify with a few examples:

  • For n=2: Sum is 0+1+1=2. The code computes target=4, remainder=4, F(4)=3, (3-1) mod10=2 ✔️
  • For n=6: Sum is 0+1+1+2+3+5+8=20. Last digit is 0. Code: target=8, remainder=8, F(8)=21, (21-1) mod10=0 ✔️

内容的提问来源于stack exchange,提问作者Veera Venkata Durga Jagadeesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:09:33