Question
What are the possible ways to solve a stack overflow caused by an recursive algorithm?
Example
I'm trying to solve Project Euler problem 14 and decided to try it with a recursive algorithm. However, the program stops with a java.lang.StackOverflowError. Understandably. The algorithm indeed overflowed the stack because I tried to generate a Collatz sequence for a very large number.
Solutions
So I was wondering: what standard ways are there to solve a stack overflow assuming your recursive algorithm was written correctly and would always end up overflowing the stack? Two concepts that came to mind were:
- a) tail recursion
- b) iteration
- tail recursion
- iteration
Are ideas a(1) and b(2) correct? Are there other options?
Edit
It would help to see some code, preferably in Java, C#, Groovy or Scala.
Perhaps don't use the Project Euler problem mentioned above so it won't get spoiled for others, but take some other algorithm. Factorial maybe, or something similar.