My assignment is write a method that reduces a BigInteger using recursion. If the number is even, split it in half then repeat the process, if the number is odd, then multiply it by 3, add 1, and repeat the process, while keeping track of the number of times this happens.
The recursion continues until the number reaches 1, then I return the amount of times this process has occurred.
I think my methods should work fine. They don't. They reduce the BigInteger to 1, then it begins looping upwards to a random number. I don't understand why. Any help would be appreciated.
EDIT: What I mean by 'looping upwards': After the big int is reduced to 1, the method continues 'looping' and every time it loops, the number grows, also the counter diminishes as the method loops. There's nothing in the method to account for that so I don't know why it does it. That explanation doesn't really help, but I put SystemPrintLn's everywhere and saw it do it.
public int Problem9(BigInteger value) {
BigInteger zero = BigInteger.valueOf(0);
BigInteger one = BigInteger.valueOf(1);
BigInteger two = BigInteger.valueOf(2);
BigInteger three = BigInteger.valueOf(3);
int count = reduceBigInt(value, zero, one, two, three, 1);
return count;
}
public int reduceBigInt(BigInteger num, BigInteger zero,
BigInteger one, BigInteger two, BigInteger three, int i) {
if (num.equals(one))
return i;
else if ((num.remainder(two)) == zero)
reduceBigInt((num.divide(two)), zero, one, two, three, i++);
else
reduceBigInt((num.multiply(three).add(one)), zero, one, two, three, i++);
return i;
}
Here is an example.
The BigInteger class conveniently offers instances for common values, ZERO, ONE, TWO, etc.
The result of f(new BigInteger("123")) would be 46.
Here is an output.