captaincrunch 1 day ago

This is fast, READABLE, and accurate:

bool is_leap_year(uint32_t y) { // Works for Gregorian years in range [0, 65535] return ((!(y & 3)) && ((y % 25 != 0) || !(y & 15))); }

3
andrepd 1 day ago

This impl is mentioned in TFA.. It's much slower and includes branches.

hoten 1 day ago

I'd expect even without optimizations on, there wouldn't be branches in the output for that code.

kragen 1 day ago

There are, even with optimizations on. You could have checked: https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(filename...

I didn't find any way to get a compiler to generate a branchless version. I tried clang and GCC, both for amd64, with -O0, -O5, -Os, and for clang, -Oz.

mmozeiko 1 day ago

If you change logic and/or to bitwise and/or then it'll be branchless.

windward 16 hours ago

>READABLE

Great. It will be useful for the exhaustive tests of the faster version.

kragen 1 day ago

You commented out your entire function body and the closing }. Also, on 32-bit platforms, it doesn't stop working at 65535.

captaincrunch 1 day ago

just a formatting issue on my side, there were \n.

archargelod 15 hours ago

This website eats newlines, unless you double them (one of the annoying features of markdown). You can use codeblocks by putting 4 spaces before each line:

    int main() {
        // this should be properly formatted
        return 0;
    };

kragen 8 hours ago

If you fix it, other people can test your code without having to fix the syntax themselves first.