Strange Counter

  • + 0 comments

    O(1) solution

    #include <stdio.h>
    #define POW(k) (((k)&(k-1)) == 0)
    #define asm __asm__
    
    int main() {
        long t, start;
        scanf("%li", &t);
        if((t+2) % 3 == 0 && POW((t+2)/3)) {
            printf("%li\n", t+2);
        } else {
            start = (t+2)/3;
            asm("movq %0, %%r8"::"r"(start));
            asm("bsr %r8, %rcx");
            asm("movq $0x01, %rax");
            asm("shl %cl, %rax");
            asm("movq %%rax, %0":"=r"(start));
            printf("%li\n", 6*start-2-t);
        }
        return 0;
    }