I recently tried to solve Problem 23 Project Euler . To do this, I first create a list of all the plentiful numbers, called abundants.
Next, I sort through this list and build another list of all sums of plentiful numbers that are below a certain limit. Now I noticed something strange. I use a nested loop to repeat twice in a list. But if I use an array to store the amount, it takes a few seconds, if I add the amount to an ArrayList, it takes several hours. What is the reason for this? I thought that an expensive operation is two nested loops, but it looks like an expensive operation is ArrayList # add. Any hints why this is so?
Here's the code for the array:
for (int i = 0; i < abundants.size(); i++) {
for (int j = 0; j < abundants.size(); j++) {
int tot = abundants.get(i) + abundants.get(j);
if (tot <= limit)
isSum[tot] = true;
}
}
}
Here is the code for ArrayList:
ArrayList<Integer> sums = new ArrayList<Integer>();
for (int i = 0; i < abundants.size(); i++) {
for (int j = 0; j < abundants.size(); j++) {
int s = abundants.get(i) + abundants.get(j);
if (!sums.contains(s) && s < limit) {
sums.add(s);
}
}
}
anon