Repeated integer division by a runtime constant value

前端 未结 3 1673
暗喜
暗喜 2020-12-08 15:23

At some point in my program I compute an integer divisor d. From that point onward d is going to be constant.

Later in the code I will divi

3条回答
  •  攒了一身酷
    2020-12-08 15:52

    The book "Hacker's delight" has "Chapter 10: Integer division by constant" spanning 74 pages. You can find all the code examples for free in this directory: http://www.hackersdelight.org/hdcode.htm In your case, Figs. 10-1., 10-2 and 10-3 are what you want.

    The problem of dividing by a constant d is equivalent to mutiplying by c = 1/d. These algorithms calculate such a constant for you. Once you have c, you calculate the dividend as such:

    int divideByMyConstant(int dividend){
      int c = MAGIC; // Given by the algorithm
    
      // since 1/d < 1, c is actually (1<>= k; // Manual floating point number =)
    
      return (int)tmp;
    }
    

提交回复
热议问题