除法算法-时间复杂度

发布于 2024-07-18 07:02:44 字数 421 浏览 6 评论 0原文

谁能帮忙解释一下这个算法的时间复杂度,以及为什么它是 O(n^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(x/2, y)
    q = 2q
    r = 2r

    if x is odd:
        r = r + 1

    if r >= y:
        r = r - y
        q = q + 1

    return (q,r)

Can anyone help with with the time complexity of this algorithm, and why it is O(n^2). A step by step explanation would be helpful, thanks!

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(x/2, y)
    q = 2q
    r = 2r

    if x is odd:
        r = r + 1

    if r >= y:
        r = r - y
        q = q + 1

    return (q,r)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

木森分化 2024-07-25 07:02:44

由于递归,divide() 最多被调用 n 次。

假设对 n 位整数进行简单算术需要 O(n) 时间。 (我所知道的所有大整数实现都是如此——例如,在 Python 中,向大整数加 1 会复制整个结果。)

然后我们有有限数量的 O(n) 操作最多发生 n 次。 这需要 O(n^n) 时间。

def divide(x, y):
    assert y >= 1
    if x == 0:
        return 0, 0
    q, r = divide(x // 2, y)
    q *= 2
    r *= 2
    if x & 1:
        r += 1
    if r >= y:
        r -= y
        q += 1
    return q, r

Due to the recursion, divide() is called up to n times.

Suppose simple arithmetic on n-bit integers takes O(n) time. (This is true in all the big integer implementations I know about -- in Python, for example, adding 1 to a big integer copies the whole thing.)

Then we have a finite number of O(n) operations happening up to n times. This takes O(n^n) time.

def divide(x, y):
    assert y >= 1
    if x == 0:
        return 0, 0
    q, r = divide(x // 2, y)
    q *= 2
    r *= 2
    if x & 1:
        r += 1
    if r >= y:
        r -= y
        q += 1
    return q, r
甩你一脸翔 2024-07-25 07:02:44

最坏的情况是 O(n),其中 x 中的每一位都是 1(例如 0xffff)。 诀窍是将递归转换为迭代。

The worst case, where every bit in x is 1 (e.g. 0xffff), is O(n). The trick is to convert the recursion into an iteration.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文