[英]How would you implement a O(C^n) time complexity function using for loops?
The only thing I can think of uses Math.pow() to calculate n before the loop and seems like a cop out. 我唯一想到的是使用Math.pow()在循环之前计算n,并且看起来像个警察。
C=2 in this example: 在此示例中,C = 2:
var oCN = function (n)
{
var j = Math.pow(2, n);
for (var i = 0; i <= j; i++) {
console.log('cactus');
};
return;
}
A recursive algorithm like this one would grow exponentially with respect to n
: 像这样的递归算法将相对于n
呈指数增长:
var oCN = function (C, n)
{
if (n < 1) { console.log('cactus'); return; }
for (var i = 0; i < C; i++) {
oCN(C, n-1);
}
}
The number of logged cacti is in the case of this algorithm is exactly C^n
, which is of course O(C^n)
. 在此算法的情况下,登录的仙人掌数正好是C^n
,当然是O(C^n)
。 Eg. 例如。 oCN(2, 4)
logs cactus
16 times, oCN(2, 5)
logs it 32 times, etc. oCN(2, 4)
记录cactus
16次, oCN(2, 5)
oCN(2, 4)
记录cactus
32次, oCN(2, 5)
。
You won't typically see a lot of day-to-day algorithms that work in exponential time. 通常,您不会看到很多在指数时间内工作的日常算法。 If something is being done in exponential time there is a good chance the input size or constants are such that the big-O complexity doesn't matter very much at all (or at least, the implementer doesn't care very much), and so you probably won't be sitting around analyzing the complexity. 如果某项事情是在指数时间内完成的,那么输入的大小或常量很有可能使big-O的复杂性根本无关紧要(或者至少实现者不太在意),并且因此您可能不会坐在那里分析复杂性。 Most normal stuff programmers want to do can either be done with a polynomial time algorithm right off the bat or with some fudging and sacrificing. 程序员想要做的大多数普通的事情可以立即使用多项式时间算法来完成,也可以通过一些伪造和牺牲来完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.