【问题标题】:Can anyone explain how this division algorithm works?谁能解释这个除法算法是如何工作的?
【发布时间】:2016-03-05 04:17:36
【问题描述】:

我在算法教科书中看到了这一点。我对中间递归函数感到困惑。如果你能用一个例子来解释一下,比如 4/2,那就太好了!

function divide(x, y) 
Input: Two n-bit integers x and y, where y ≥ 1 
Output: The quotient and remainder of x divided by y

if x = 0: return (q, r) = (0, 0) 
(q, r) = divide(floor(x/2), y) 
q = 2 · q, r = 2 · r 
if x is odd: r = r + 1 
if r ≥ y: r = r − y, q = q + 1 
return (q, r)

【问题讨论】:

    标签: algorithm division integer-division


    【解决方案1】:

    您会看到它可以被 2 整除多少次。这实际上是在执行位移位并在二进制数字上进行操作。更有趣的情况是 13/3(13 是二进制的 1101)。

    divide(13, 3)  // initial binary value - 1101
      divide(6, 3)  // shift right - 110
        divide(3, 3)  // shift right - 11
          divide(1, 3)  // shift right - 1 (this is the most significant bit)
            divide(0, 3)  // shift right - 0 (no more significant bits)
            return(0, 0)  // roll it back up
          return(0, 1) // since x is odd (1)
        return(1, 0) // r = r * 2 = 2; x is odd (3) so r = 3 and the r > y condition is true      
      return(2, 0)  // q = 2 * 1; r = 2 * 1 - so r >= y and q = 2 + 1
    return(4, 1)  // q = 2 * 2; x is odd to r = 0 + 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      • 1970-01-01
      相关资源
      最近更新 更多