Integer log10 in Rust and C
Following the stabilization of the integer log10 interface in Rust 1.67 , I got interested in seeing whether it could be optimized. There's well known lore in this area starting from the omnipresent Hackers Delight implementation, to more recent thoughts (discussed here ). I had a bit of a new thought on how to express it that turned out inferior for reasons I find interesting. Let's dive in. Most of the approaches involve a two-step process: (1) Use integer log2 to approximate the log10 result; and (2) check to see if the value exceeds the next log10 threshold and increment if so. To make that clear, consider the number 14. Its rounded-down log2 is 3. In that range one can find the numbers 8-15. Therefore, one would map 3 -> 0 (i.e., "numbers whose log2 is 3 should be assumed to be 10^0"), but then test to see if the number was >= 10, in which case, it gets an extra boost. This algorithm was succinctly described by Steve Cannon in a stackoverflow post , using ...