Scala factorial on large numbers sometimes crashes and sometimes doesn't?

Tail-call optimization will only work in Scala if the recursive call is the last statement in the function. It's very limited. The Scala book says: ... tail-call optimization is limited to situations in which a method or nested function calls itself directly as its last operation, without going through a function value or some other intermediary In your case, the recursive call is part of a larger expression, and is not itself the very last operation - the last operation here is the multiplication This article demonstrates how to make it work: class Factorial { def factorial(n: Int): Int = { def factorialAcc(acc: Int, n: Int): Int = { if (n.

Tail-call optimization will only work in Scala if the recursive call is the last statement in the function. It's very limited. The Scala book says: ... tail-call optimization is limited to situations in which a method or nested function calls itself directly as its last operation, without going through a function value or some other intermediary.In your case, the recursive call is part of a larger expression, and is not itself the very last operation - the last operation here is the multiplication.

This article demonstrates how to make it work: class Factorial { def factorial(n: Int): Int = { def factorialAcc(acc: Int, n: Int): Int = { if (n.

– Liran Orevi Jul 27 '09 at 10:35 You're right, I misread your code (I've reformatted it to make it a bit clearer, and I'll update my answer). – skaffman Jul 27 '09 at 10:53 It worked, well done, also thanks for the link to the great article on the subject. – Liran Orevi Jul 28 '09 at 13:13.

In Scala 2.8 you can use the @tailrec annotation when you expect that tail call optimization should be used, and get a warning if it's not possible for the compiler to do so.

Not sure it was released yet. Scala-lang.Org/downloads – Liran Orevi Sep 23 '09 at 8:44.

If you really have large numbers, there are many approximations, for example this one in Scala that uses prime factorization: class SwingFactorial(n: Int) { def name() = "SwingFactorial" def value(): BigInt = { if (n = 0, but was " + n) } ndiv2OddFact = BigInt(1) ndiv4OddFact = ndiv2OddFact return oddFactorial(n) >> 1 return product(m - hlen * 2, len - hlen) * product(m, hlen) } private var ndiv4OddFact = BigInt(1) private var ndiv2OddFact = BigInt(1) } Usage: var fs = new SwingFactorial(n) val a = fs.value().

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions