The Forum > Programming Knowledge Base > java help
![]() Original issue I am given a random integer that is supposed to represent a number of basketballs. If the integer is even, I can take away half of the balls. If the number is divisible by 5, I can take away 42 balls. And if the number is divisble by 3 or 4, I can take the last two digits multiplied together and subtract that from the number of balls. The goal is to end up with 42 balls. How would I go about calculating all possible cases where I can reach that goal? |
![]() Proposed solution This is a problem with recursion. Your terminating condition is when the number of balls is less than or equal to 42. Every operation you describe reduces the number of balls and approaches the terminating condition. private static boolean valid(int balls) { if (balls < 42) return false; if (balls == 42) return true; // if even, cut them in half and check again... if (balls % 2 == 0) { if (valid(balls / 2)) { return true; } } // if divisible by 5, remove 42 of them and check again... if (balls % 5 == 0) { if (valid(balls - 42)) { return true; } } // if divisible by 3 or 4, do the digit thing and check again... if (balls % 3 == 0 || balls % 4 == 0) { int lastDigit = balls % 10; int secondToLast = (balls % 100) / 10; if (valid(balls - lastDigit * secondToLast)) { return true; } } return false; } |
DIAV said: You only need to check the second to last, since if the last is 0 it is divisible by 2 (and 5). Wrong. Case: 60 0 == 60 % 2: valid(60/2)? 30 < 42, no 0 == 60 % 5: valid(60-42)? 18 < 42, no 0 == 60 % 3: 0 != secondtolast(60): valid(60-6*0)? Iunno, try valid(60). Oh, wait, infinite recursion! (In short, yes, check both the last and second to last digits.) |
The Forum > Programming Knowledge Base > java help


