In fact, this would be a good question that could be asked at the interview, because it is simple enough for you to write on a white board, but difficult enough for him to knock someone over if they did not think about This is thorough enough. In addition, you can also use two different answers, which differ significantly from the implementation.
Questions for ordering
If order matters, then any solution must allow zero for any of the variables; thus, the most direct solution would be as follows:
public class Combos { public static void main() { long counter = 0; for (int a = 0; a <= 500; a++) { for (int b = 0; b <= (500 - a); b++) { for (int c = 0; c <= (500 - a - b); c++) { for (int d = 0; d <= (500 - a - b - c); d++) { counter++; } } } } System.out.println(counter); } }
Which returns 2656615626.
Order doesn't matter
If the order does not matter, then the solution is not much more complicated, since you just need to make sure that zero is not possible if the sum is not already found.
public class Combos { public static void main() { long counter = 0; for (int a = 1; a <= 500; a++) { for (int b = (a != 500) ? 1 : 0; b <= (500 - a); b++) { for (int c = (a + b != 500) ? 1 : 0; c <= (500 - a - b); c++) { for (int d = (a + b + c != 500) ? 1 : 0; d <= (500 - a - b - c); d++) { counter++; } } } } System.out.println(counter); } }
Which returns 2573155876.
rjzii
source share