Today I was going through SRM-556 DIV-2 500 question.
I tried to implement the solution in Java. It didn't work. Then implemented in C++. It worked. In Java I got stackoverflow error. While in C++, it ran perfectly.
For the last test cases, the number of recursive calls made is 25600. Doesn't Java have enough space to accomodate this much instances (copies) of program.
Please help me why I am getting such strange behavior in Java????
There is no "stack size in C++" or "stack size in Java" — these values could be configured at compilation / runtime (though at TopCoder you, perhaps, could not control it).
You wrote:
But stack size is not measured in stack frames. Stack size is defined in bytes (and sometimes you can change this setting, for example from command line) — and it depends on your implementation how much each stack frame takes. For example you could try and make the method static, or use arguments of smaller size (shorts, for example). However, I do not believe such monkeying is a good approach.
I think when you see that recursion could be too deep, you need to use external stack (and iteration) or something like it. It would never do to write programs which are at the edge of failing by design.
Try this
Executes .run() method with 8Mb stacksize. (Last parametr == (1 << 23) )
In your case:
Since this is competitive problem, I am not allowed to use threads.... :)
It is not cheating, it is quite old recipe found in old submission of Petr Mitrichev, for example. The idea is that newly created threads could use larger stack. However I do not remember whether it makes sense for nowadays versions of java.
Read the post thoroughly and perform some experiments if you want.