A classic performance improvement in calculating a series of numbers is to take advantage of previous work.
If the cube of X
is Y
, then the cube of X+1
is Y + 3*X*(X+1) + 1
.
With such a simple function of Y=X*X*X
, I doubt it will be faster than List numbers 1 to cuberoot(n), but the idea is useful in a general sense.
Below is a C code that hopefully expresses the idea clear enough for a python
user.
void cubes(unsigned long limit) {
unsigned i = 1;
unsigned long cube = 1;
while (cube <= limit) {
printf("%u %lu\n", i, cube);
cube += 3L*i*(i + 1) + 1;
i++;
}
}
int main(void) {
cubes(9238899039);
return 0;
}
Output
1 1
2 8
3 27
...
2096 9208180736
2097 9221366673
2098 9234565192
Another math solution takes advantage of differences of differences. No multiplication needed.
void cubes(unsigned long limit) {
unsigned i = 1;
unsigned d1 = 0;
unsigned long d2 = 1;
unsigned long cube = 1;
while (cube <= limit) {
printf("%u %lu\n", i, cube);
d1 += 6;
d2 += d1;
cube += d2;
i++;
}
}
store.append(i)
did you actually mean to storestore.append(i*i*i)
? \$\endgroup\$