时间复杂性的一个基本例子

时间:2014-09-04 18:52:22

标签: algorithm recursion data-structures complexity-theory time-complexity

我遇到了一个例子,想要计算这段代码的顺序(时间复杂度)。有人可以帮我理解如何计算这段代码的顺序:

f(n)
{
    i=0;
    while (n>0) {
        n=n/10;
        i=i+1;
    }
    return (i);
}

事实上,我认为订单是O(n/10)。愿任何专家帮助我吗?

1 个答案:

答案 0 :(得分:3)

时间复杂度为O(log n),因为在每次迭代时,n除以10。

使用Master theorem证明:在您的情况下,a = 1b = 10c = log(a) = 0k = 0T(n)=O(log n)