
Computing Trailing Zeros (2009) - espeed
http://7ooo.mooo.com/text/ComputingTrailingZerosHOWTO.html
======
kccqzy
I was once asked this exact question in a technical interview. I used
__builtin_ctzll and that dumbfounded the interviewer. (Disclaimer: this may or
may not be a good thing to do in an interview depending on the
role/interviewer.)

In the real world, you probably want to use this builtin or something provided
by the compiler/standard library as opposed to rolling your own.

------
bsder
More Bit Twiddling Hacks:
[https://graphics.stanford.edu/~seander/bithacks.html](https://graphics.stanford.edu/~seander/bithacks.html)

------
nemo1618
Pretty neat. You can see this exact approach in the Go standard library:
[https://golang.org/src/math/bits/bits.go#L35](https://golang.org/src/math/bits/bits.go#L35)

Nowadays, of course, ctz gets compiled down to a single instruction (e.g. bsf
on x86) :)

------
tromp
While the papers mentions odd numbers as a possible special case in a
sidenote, the real special case is x=0. The given expression

    
    
        size_t i = ((x & -x) * debruijn) >> 27;
    

treats x=0 the same as odd x, since 0 _debruijn >>27 == 1_debruijn>>27 == 0.

------
pmiller2
Mirror:
[http://web.archive.org/web/20190410000033/http://7ooo.mooo.c...](http://web.archive.org/web/20190410000033/http://7ooo.mooo.com/text/ComputingTrailingZerosHOWTO.html)

------
FabHK
Anyone got a cache? I can't access it.

The title reminded me of this Project Euler problem named "Factorial trailing
digits":

[https://projecteuler.net/problem=160](https://projecteuler.net/problem=160)

~~~
mjcohen
That's a standard log(n) algorithm. It's harder to calculate the first nonzero
digit.

~~~
FabHK
By that you mean the first digit?

