Evan Bailey Evan Bailey - 29 days ago 14
Java Question

Getting stack overflow when trying to have the method repeat when there is an even number inputted

I have this code :

public static int rsnpeasant(int x, int y) {

if ((y & 1) == 0) {
y = y / 2;
x = x * 2;
rsnpeasant(x, y);
} else {
sum = sum + x;
y = y / 2;
y = y - 1 / 2;
x = x * 2;

if (y == 1) {
sum = total;
return total;

} else {
rsnpeasant(x, y);
}
}

total = sum;
return total;
}


The error is happening on the first
rsnpeasant(x,y);
line in the first
if
statement. It seems to be forever looping to that line even though it's supposed to go to the
else
statement if
y
is odd. If
y
is divided by
2
it should become odd at some point.
http://mathforum.org/dr.math/faq/faq.peasant.html is what im trying to code

Answer

Your principal problem is that you are trying to divide an int primitive type, if y = 1, dividing that value by 2 will return 0, then you pass it to the method again, it will always be stuck in the first if statement.

You should return a double, float or bigdecimal in your method, and use one of those types for the parameters too.