3 ms·
Compilers can and do replace some (simple) algorithms with a better one. At https://stackoverflow.com/questions/74417624/how-does-clang-generate-non-looping-co
by eesmith 3y ago
Compilers can and do replace some (simple) algorithms with a better one.
At https://stackoverflow.com/questions/74417624/how-does-clang-generate-non-looping-code-for-sum-of-squares https://stackoverflow.com/questions/74417624/how-does-clang-... is someone asking why the compiler replaced:
int a = 0;
while (n--)
a += (n * n);
an O(n) algorithm, with the O(1) equivalent of:
a = n * (n-1) / 2 + n
- zimpenfish 3y agoI think your `n * (n-1) / 2 + n` should be `n(n+1)(2n+1)/6` according to the SO article. `n * (n-1) / 2 + n` would be the sum of numbers, not sum of squares.
- eesmith 3y agoThank you for the correction!