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

使用斐波那契通项公式求解爬楼梯问题时输出结果错误该如何解决

问题原因

你调用的是标准斐波那契数列第n项的通项公式,但爬楼梯问题的解对应的斐波那契下标存在1位偏移,两者的对应关系如下:

  • 标准斐波那契定义:F(1)=1,F(2)=1,F(3)=2,F(4)=3,F(5)=5,F(6)=8
  • 爬楼梯问题解对应:n阶楼梯的方式数 = F(n+1)

你当前代码计算的是F(n),因此会出现staircase(4)返回F(4)=3、staircase(5)返回F(5)=5的情况,和预期的F(5)=5、F(6)=8刚好差一位。

修正代码
import math

def staircase(n):
  term_a = ((1 + math.sqrt(5))/2) ** (n+1)
  term_b = ((1 - math.sqrt(5))/2) ** (n+1)
  numerator = term_a - term_b
  denominator = math.sqrt(5)
  return round(numerator/denominator)
  
print(staircase(4))
# 5
print(staircase(5))
# 8
注意事项

由于通项公式依赖浮点数运算,n值较大时可能出现精度偏差,使用round()替代直接int()转换可以避免小范围的精度误差导致结果错误。

内容的提问来源于stack exchange,提问作者mchd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:54:02