For an assignment in a Math class, I was given the following Java function:
public static int foo(int x, int y) {
if (x==0) return 1;
if (x<=y) return foo(x,y-1);
return foo(y,x);
}
We are now supposed to show if it is possible to construct a mathematical set T
, which when implemented as a Java class and used as inputs for the function, will always lead the function to terminate. Also it must not be possible to add another element to T so that the function will still terminate.
public static T foo(T x, T y) { . . . }
It is fairly obvious that the function cannot terminate for negative parameters. Therefore set T will necessarily only include non-negative integers. But for large elements of int
the function will also result in a stack overflow. That makes sense as the maximum value for int
is 2,147,483,647. So foo(2147483647, 2147483647)
will result in more than 4 billion recursive calls of the function.
To get a sense of where this is going, I tried out several different inputs. I always used the same inputs for x
and y
as that maximizes the number of recursive calls. That's because if foo(1,a)
terminates but foo(a,a)
doesn't, then a
should not be part of the set, as it can lead to non-terminating calls.
The odd thing with this trial and error approach is, that the for some inputs, e.g. foo(5600, 5600)
, the function sometimes returns 1
and sometimes it leads to a stack overflow error.
Shouldn't the same call lead to the same result every time? Why does the stack sometimes overflow and sometimes not? Is the stack shared with other programs? Is there a way to make the behavior more predictable? And is it possible to specify a set T as asked in the assignment?