Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

[PROG CHALLENGE #024] Non-Corporate Edition

Name: Anonymous 2020-01-13 16:05

Write a function:

int solution(int N);

that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.

For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.

Name: Anonymous 2020-01-14 17:38

I found bsf has latency of 3, so i rewrote it to use less iterations to squeeze more performance:
v1.15 of bingap:
int bingap32(u32 N){// a faster pure C bingap using GCC intrinsics
int maxGap=0,gap=0;
do{
maxGap=gap>maxGap?gap:maxGap;//if N has bits set maxGap(initial iteration does nothing)
N>>=__builtin_ctz(N);//strip trailing zeros
N>>=__builtin_ctz(~N);//strip trailing ones
gap=__builtin_ctz(N);//count trailing zeros
}while(N);
return maxGap;
}

Assembler:
00000000000012c0 <bingap32>:
bingap32():
12c0: 0f bc cf bsf %edi,%ecx
12c3: 31 d2 xor %edx,%edx
12c5: 31 c0 xor %eax,%eax
12c7: 66 0f 1f 84 00 00 00 nopw 0x0(%rax,%rax,1)
12ce: 00 00
12d0: 39 d0 cmp %edx,%eax
12d2: 0f 4c c2 cmovl %edx,%eax
12d5: d3 ef shr %cl,%edi
12d7: 89 f9 mov %edi,%ecx
12d9: f7 d1 not %ecx
12db: 0f bc c9 bsf %ecx,%ecx
12de: d3 ef shr %cl,%edi
12e0: 0f bc d7 bsf %edi,%edx
12e3: 89 d1 mov %edx,%ecx
12e5: 85 ff test %edi,%edi
12e7: 75 e7 jne 12d0 <bingap32+0x10>
12e9: c3 retq
12ea: 66 0f 1f 44 00 00 nopw 0x0(%rax,%rax,1)

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List