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

Scala阶乘函数返回结果存疑:调用fact(4)得24而非预期12

Understanding Your Scala Factorial Function Result

Hey Tyler, let's walk through exactly why fact(4) returns 24 instead of the 12 you expected—your recursive function is working correctly, you just missed a step in the recursive breakdown!

First, let's recap your function definition (which is perfectly valid for calculating factorials):

def fact(n:Int):Int = if (n<2) 1 else n*fact(n-1)

Let's expand the recursive calls step by step for fact(4):

  • When you call fact(4), since 4 is not less than 2, it evaluates to 4 * fact(3)
  • Next, fact(3) evaluates to 3 * fact(2) (3 is also not <2)
  • Then fact(2) evaluates to 2 * fact(1) (2 is not <2)
  • Finally, fact(1) hits the base case: since 1 < 2, it returns 1

Now let's compute the results working backwards:

  • fact(2) = 2 * 1 = 2
  • fact(3) = 3 * 2 = 6
  • fact(4) = 4 * 6 = 24

Your confusion came from assuming fact(3) equals 3, but remember—fact(3) doesn't just return 3, it returns 3 multiplied by the result of fact(2), which itself is 2 multiplied by fact(1). That's the magic (and sometimes tricky part) of recursion: each call depends on the next smaller call until we hit the base case.

If you want to verify this further, try printing intermediate values by modifying your function slightly:

def fact(n:Int):Int = {
  println(s"Calculating fact($n)")
  if (n<2) 1 else n*fact(n-1)
}

Running fact(4) will show you each step of the recursion, making it even clearer how the values build up to 24.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:45:47