【发布时间】:2017-03-06 23:43:52
【问题描述】:
以下函数的运行时间复杂度是O(1)吗?
int pow(int a, int n) {
if (n == 0) {
return 1;
}
if (n % 2 == 1) {
return pow(a, n / 2) * pow(a, n / 2) * a;
} else {
return pow(a, n / 2) * pow(a, n / 2);
}
}
我有这样的印象,因为代码中只有 if 语句,没有循环。我以前从未使用过 Big-O 和递归,我在网上找不到任何好的资源。
【问题讨论】:
-
嗯,如果 n 为 0,它需要恒定的时间,否则无论 pow(a,n/2) 需要多少操作,它至少需要两倍。
-
啊,好吧。所以最好的情况是 O(n) 和 O(1)?
标签: c++ algorithm recursion time-complexity big-o