方案中acc函数的时间复杂度?

发布于 2025-01-05 07:51:00 字数 245 浏览 4 评论 0原文

我一直试图找到该函数仅针对其中一个参数的严格限制时间复杂度。我认为它是 O(p^2) (或者更确切地说是大 theta),但我不再确定了。

(define (acc p n)
  (define (iter p n result)
    (if (< p 1) 
        result
        (iter (/ p 2) (- n 1) (+ result n))))
  (iter p n 1))

I have been trying to find a tight bound time complexity for this function with respect to just one of the arguments. I thought it was O(p^2) (or rather big theta) but I am not sure anymore.

(define (acc p n)
  (define (iter p n result)
    (if (< p 1) 
        result
        (iter (/ p 2) (- n 1) (+ result n))))
  (iter p n 1))

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

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

发布评论

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

评论(2

挽容 2025-01-12 07:51:00

@sarahamedani,为什么这是 O(p^2)?对我来说,它看起来像 O(log p) 。运行时应该对n 的值不敏感。

您正在对一系列数字求和,从 n 开始倒数。 iter 迭代的次数取决于 p 可以减半多少次而不小于 1。换句话说,就是最左边 '1' 位的位置p 减一是 iter 迭代的次数。这意味着 iter 运行的次数与 log p 成正比。

@sarahamedani, why would this be O(p^2)? It looks like O(log p) to me. The runtime should be insensitive to the value of n.

You are summing a series of numbers, counting down from n. The number of times iter will iterate depends on how many times p can be halved without becoming less than 1. In other words, the position of the leftmost '1' bit in p, minus one, is the number of times iter will iterate. That means the number of times iter runs is proportional to log p.

久随 2025-01-12 07:51:00

您可以尝试观察它,或者更系统地了解它。假设我们从头开始这样做,我们应该尝试从函数定义构建递归关系。

目前,我们可以假设一个非常简单的机器模型,其中算术运算和变量查找都是常数时间。

iter-cost 为计算计算 iter 所需步数的函数名称,并令其为 p 的函数,因为 iter 的终止仅取决于 p。然后您应该能够为 iter-cost(0) 编写表达式。您可以对 iter-cost(1)iter-cost(2)iter-cost(3)执行此操作吗>迭代成本(4)

更一般地说,给定一个大于零的 p,你能表达 iter-cost(p) 吗?它将采用常量和对 iter-cost 的循环调用。如果您可以将其表达为递归形式,那么您就可以更好地以封闭形式表达它。

You might try to eyeball it, or go from it more systematically. Assuming we're doing this from scratch, we should try build a recurrence relation from the function definition.

We can assume, for the moment, a very simple machine model where arithmetic operations and variable lookups are constant time.

Let iter-cost be the name of the function that counts how many steps it takes to compute iter, and let it be a function of p, since iter's termination depends only on p. Then you should be able to write expressions for iter-cost(0). Can you do that for iter-cost(1), iter-cost(2), iter-cost(3), and iter-cost(4)?

More generally, given an p greater than zero, can you express iter-cost(p)? It will be in terms of constants and a recurrent call to iter-cost. If you can express it as a recurrence, then you're in a better position to express it in a closed form.

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