private static int chain(int n){
int count = 0;
while(n > 1){
if(n % 2 == 0){
count++; //the value is not stored
return chain(n/2);
}
count++; //same thing
return chain(3*n+1);
}
return count; //prints the initial value (0)
}
}
I need to print the number of times the chain method reoccurs.
How about this:
public static int chain(int n) {
return chain(n, 0);
}
private static int chain(int n, int count) {
if (n > 1) { // no need for a while-loop, it will never get past 1 iteration
if (n % 2 == 0) {
return chain(n / 2, count + 1);
}
return chain(3 * n + 1, count + 1);
}
return count;
}
To me, this seems cleaner than declaring a static field outside of the method, primarily because I wouldn't want to worry about having to reset the static field to 0 every time I call chain
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With