The following program, was compiled and tested, it sometimes return the result, and sometimes fills the screen with
java.lang.StackOverflowError
at scala.BigInt$.apply(BigInt.scala:47)
at scala.BigInt.equals(BigInt.scala:129)
at scala.runtime.BoxesRunTime.equals(Unknown Source)
at bigint$.factorial(fact2.scala:3)
at bigint$.factorial(fact2.scala:3)
...
The program:
object bigint extends Application {
def factorial(n: BigInt): BigInt = if (n == 0) 1 else n * factorial(n-1)
println("4391! = "+factorial(4391))
}
My questions:
- Is it because there is a stack overflow on the JVM, which sometimes happens and sometimes doesn't?
- Is this nondeterministic behavior considered a bug?
- I assume Scala did not tail-recursed this? how can I make it tail-recurse this?
Details:
Scala compiler version 2.7.5.final -- Copyright 2002-2009, LAMP/EPFL Scala code runner version 2.7.5.final -- Copyright 2002-2009, LAMP/EPFL
java version "1.6.0_0" OpenJDK Runtime Environment (build 1.6.0_0-b11) OpenJDK Client VM (build 1.6.0_0-b11, mixed mode, sharing)
Ubuntu 2.6.24-24-generic