You can pass the prime number "depth" to a recursive function and increase it with each subsequent call. If it becomes greater than the maximum allowable depth, throw an exception on the right, instead of waiting until it gets too late, and a terrible StackOverflow exception StackOverflow .
Such security mechanisms (increment counter, check that it is not stupidly large) can also be useful in while loops, where a small error can cause an infinite loop that consumes a huge amount of CPU.
On large systems with many users (such as websites), it is sometimes better to take precautions such as these with recursion and loops, since the consequences can go far beyond a single web page or system user. This is not a pretty code, and purists will undoubtedly refuse it, but it is efficient, secure and pragmatic.
Ian mercer
source share