Skip to content

Commit 0e28286

Browse files
committed
P451: Tweaked Java solution slightly for clarity.
1 parent 27a0b8d commit 0e28286

File tree

1 file changed

+14
-17
lines changed

1 file changed

+14
-17
lines changed

java/p451.java

+14-17
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,9 @@ public String run() {
3030

3131
// Process every integer in range
3232
solutions = new IntArrayArray(LIMIT / 2 + 1); // Uses about 2 GiB of memory
33-
solutions.append(new int[]{});
34-
solutions.append(new int[]{});
35-
solutions.append(new int[]{1});
33+
solutions.append();
34+
solutions.append();
35+
solutions.append(1);
3636
long sum = 0;
3737
for (int i = 3; i <= LIMIT; i++) {
3838
int[] sols = getSolutions(i);
@@ -50,6 +50,8 @@ private int[] getSolutions(int n) {
5050
if (smallestPrimeFactor[n] == n) // n is prime
5151
return new int[]{1, n - 1};
5252
else {
53+
// Note: Changing the ArrayList<Integer> to an implementation
54+
// based on int[] does not yield meaningful speed improvement
5355
List<Integer> temp = new ArrayList<>();
5456
int p = smallestPrimeFactor[n];
5557
int[] sols = solutions.get(n / p);
@@ -60,30 +62,26 @@ private int[] getSolutions(int n) {
6062
temp.add(k);
6163
}
6264
}
63-
return toIntArray(temp);
65+
66+
// Convert List<Integer> to int[]
67+
int[] result = new int[temp.size()];
68+
for (int i = 0; i < result.length; i++)
69+
result[i] = temp.get(i);
70+
return result;
6471
}
6572
}
6673

6774

68-
private static int[] toIntArray(List<Integer> list) {
69-
int[] result = new int[list.size()];
70-
for (int i = 0; i < result.length; i++)
71-
result[i] = list.get(i);
72-
return result;
73-
}
74-
75-
7675

77-
// Conceptually like int[][], but having elements all packed into one int[]
78-
private static class IntArrayArray {
76+
// Conceptually like int[][], but having elements all packed into one int[].
77+
private static final class IntArrayArray {
7978

8079
private int[] data;
8180
private int dataLength;
8281
private int[] starts;
8382
private int index;
8483

8584

86-
8785
public IntArrayArray(int len) {
8886
data = new int[1];
8987
dataLength = 0;
@@ -95,13 +93,12 @@ public IntArrayArray(int len) {
9593
}
9694

9795

98-
9996
public int[] get(int i) {
10097
return Arrays.copyOfRange(data, starts[i], starts[i + 1]);
10198
}
10299

103100

104-
public void append(int[] arr) {
101+
public void append(int... arr) {
105102
while (dataLength + arr.length > data.length)
106103
data = Arrays.copyOf(data, data.length * 2);
107104

0 commit comments

Comments
 (0)