Hacker News new | ask | show | jobs
by deletes 4509 days ago
If your range is not too big( < 32768 ) and the divisor is constant you can do it with a single multiplication and a shift.

More complicated method: http://www.hackersdelight.org/divcMore.pdf

But the compiler will( should, look at generated code ) optimize the constant division anyway.

---

Behold, division by three using only addition and shifting( works up to 32767 ):

  unsigned int div3upto32767( unsigned int n )
  {
     return ( ( n << 13 )+( n << 11 )+( n << 9 )+( n << 7 )+( n << 5 )+( n << 3 )+( n << 1 )+n ) >> 15 ;
  }
---

This one works up to 32767, and then produces a wrong result every ~32767 numbers or so. The result is of by one. When you get over a million, every number is of by a couple of digits.

  uint64_t div3almost( uint64_t n )
  {
     n -= ( n >> 15 ) ;
     return ( ( n << 13 )+( n << 11 )+( n << 9 )+( n << 7 )+( n << 5 )+( n << 3 )+( n << 1 )+n ) >> 15 ;
  }
I don't think the additions are worth it.