【问题标题】:Algorithms - Time complexity of recursive multiplication function算法 - 递归乘法函数的时间复杂度
【发布时间】:2017-11-02 08:27:13
【问题描述】:

我将此作为测试问题来评估以下递归方法的时间复杂度。

def multiply(x,y)
if y = 0: 
   return 0
z = multiply(x,y/2) 
if y is even:
   return 2z
else :
   return x + 2z

我写了 log(n) 因为数字 y 不断减少 2 并且递归调用将在满足条件时很快结束。

【问题讨论】:

  • 您确定解决方案不是 log(y)?
  • 教授没有给我任何分数。我仍然认为它应该是 log(y)*。在与他讨论之前,我想征求专家意见。
  • 如果你在 Python 中使用multiply(10, 2) 运行它,你会得到一个递归错误:RecursionError: maximum recursion depth exceeded in comparison
  • 第二行,代码中y = 0,你确定不是y == 0?
  • @AkashdeepSaluja 这也是我的假设。

标签: algorithm runtime time-complexity big-o


【解决方案1】:

如果函数如问题中所述进行零检查,则该函数将永远不会终止。

这是一个可用的 python 版本:

def multiply(x,y):
    if y == 0:
        return 0
    z = multiply(x,y/2)
    if y % 2 == 0:
        return 2 * z
    else :
        return x + 2 * z

无论你输入什么:这都会以递归错误结束。所以复杂性是无限的。也许这是一个诡计问题。

如果你老师的意思是这样的:

def multiply(x, y):
    if 0.01 > y > -0.01:
        return 0
    z = multiply(x, y / 2)
    if y % 2 == 0:
        return 2 * z
    else:
        return x + 2 * z

那么复杂性看起来确实像log(n)

这是一些计算操作次数的复杂性基准代码:

counter = 0

def multiply(x, y):
    global counter
    counter += 1
    if 0.01 > y > -0.01:
        return 0
    z = multiply(x, y / 2)
    if y % 2 == 0:
        return 2 * z
    else:
        return x + 2 * z

for i in range(1000):
    counter = 0
    multiply(1, i)
    print(i, counter)

它打印一个本质上是对数的数字序列:

0 1
1 8
2 9
3 10
4 10
5 10
6 11
7 11
8 11
9 11
10 11
11 12
12 12
13 12
14 12
15 12
16 12
17 12
18 12
19 12
20 12
21 13
22 13
23 13
24 13
25 13
26 13
27 13
28 13
29 13
30 13
...

【讨论】:

    猜你喜欢
    • 2013-04-28
    • 1970-01-01
    • 2021-03-30
    • 2011-02-12
    • 2017-07-15
    • 1970-01-01
    相关资源
    最近更新 更多