Evan Bailey - 4 months ago 33

Java Question

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);`

`if`

`else`

`y`

`y`

`2`

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.