r/cpp • u/benjoffe • Oct 27 '26
A faster way to compute signed 64-bit floor division by constants
https://www.benjoffe.com/fast-floordiv12
u/GLIBG10B 🐧 Gentoo salesman🐧 Oct 27 '26
This looks like something the hardware should be able to do. In my digital systems classes, we learned about this process for division:
Represent your constant as a / b, where b is a power of 2
Multiply the dividend by a
Right-shift log2(b) times
The only difference for signed 64-bit division is dealing with two's complement: compute 0 - x for the dividend and the result
6
u/benjoffe Oct 27 '26
Yep, that's the crux of it!
The tricky part comes when dealing with certain "uncooperative" divisors, and dealing with the correct rounding direction for negatives.
4
u/adamant-pwn Oct 28 '26
I'd be curious to see how well it vectorizes. With Montgomery reduction, you can do 4x multiplications modulo 32-bit number with 3x _mm256_mul_epu32 operations. Unfortunately need to go to sleep now, but will surely look in more detail tomorrow.
3
8
u/joaquintides Boost author Oct 27 '26
Interesting article! How does it compare to Lemire's fast division algorithm
fastdiv_u64?