Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

In any compiled language your optimizer will do all those weird things for you, and will even handle all the different generations of CPUs for you. Compilers never give you a better algorithm if you write the wrong one.

Almost all languages have a standard library that has all the normal algorithems you would want, and where something wierd is better they have that done for you.



Compilers can and do replace some (simple) algorithms with a better one.

At 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


I 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.


Thank you for the correction!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: