大O和T(n)混淆

Big O and T(n) Confusion

本文关键字:混淆      更新时间:2023-10-16

我目前正在做一些关于大O和T(n)的作业,并且遇到了一些问题。我已经像我的教授说的那样,代入了一些数字,并得出了每个循环运行的次数,但我不知道如何从这些信息中推导出T(n)和大O。我浏览了整个网站,但似乎找不到任何帮助。这是一些没有分配的问题,但与我正在努力解决的分配问题非常相似。

如果你能一步一步地找出如何找到大O和T(n),那将非常有帮助。谢谢你的宝贵时间。

for (int i = 0; i < n; i++)
 for (int j = 0; j < i * i; j++)
 cout << j << endl;
i=1 runs 1 time
i=2 runs 4 times
i=3 runs 9 times
i=4 runs 16 times
for (int i = n; i >= 0; i -= 2)
 cout << i << endl;
n=10 runs 6 times
n=8 runs 5 times
n=6 runs 4 times
n=4 runs 3 times
n=2 runs 2 times
for (int i = 0; i < n; i++)
 for (int j = i; j > 0; j /= 2)
 cout << j << endl; 
i=16 runs 5 times
i=8 runs 4 times
i=4 runs 3 times
i=2 runs 2 times

这些都是非常简单的情况,你所要做的就是计算迭代的次数。

我们看第一个:

for (int i = 0; i < n; i++)
 for (int j = 0; j < i * i; j++)
   cout << j << endl;

对于特定的i值,我们对内循环进行i^2次迭代。因此,最内层步骤的总迭代次数为:

0^2 + 1^2 + 2^2 + ... + (n-1)^2
= (n-1)(n)(2n-1)/6  // it helps to just know the formula for sums of squares
= Ө(n^3)            // just drop all the constants

按照同样的方法处理其他两个。第二个是微不足道的(Ө(n)),尽管第三个更有趣(O(n lg n))。