Starting with the brute force approach, its pretty obvious it will O(n^4) time to execute.
If space is not a constraint, we can go for combination of list and maps.
The code is self-explanatory, we are using a nested list to keep track of all entries for a particular sum (key in map).
The time complexity is thus reduced from O(n^4) to O(n^2)
public void printAllCubes() {
int n = 50;
Map> resMap = new HashMap>();
ArrayList pairs = new ArrayList();
ArrayList allPairsList = new ArrayList();
for (int c = 1; c < n; c++) {
for (int d = 1; d < n; d++) {
int res = (int) (Math.pow(c, 3) + Math.pow(d, 3));
pairs.add(c);
pairs.add(d);
if (resMap.get(res) == null) {
allPairsList = new ArrayList();
} else {
allPairsList = resMap.get(res);
}
allPairsList.add(pairs);
resMap.put(res, allPairsList);
pairs = new ArrayList();
}
}
for (int a = 1; a < n; a++) {
for (int b = 1; b < n; b++) {
int result = (int) (Math.pow(a, 3) + Math.pow(b, 3));
ArrayList pairList = resMap.get(result);
for (List p : pairList) {
System.out.print(a + " " + b + " ");
for (Object num : p)
System.out.print(num + " ");
System.out.println();
}
}
}
}