How would you go about finding the complexity of this algorithm?

[亡魂溺海] 提交于 2019-12-02 05:52:33

We can compute the exact number of increments this code executes. First, let's replace

for k=t to o+t do

with

for k=1 to o+1 do 

After this change, two inner loops looks like this

for t=1 to o do
    for k=1 to o+1 do

The number of iterations of these loops is obviously o*(o+1). The overall number of iterations can be calculated in the following way:

We can exclude coefficients and lower order terms of the polynomial when using big-O notation. Therefore, the complexity is O(n^3).

Subtract t from the last loop so that it becomes

for k=0 to o do

Now the 2 inner most loops would run for O(o^2) time for every value of o. The answer would be

1^2 + 2^2 + ... n^2

which is equal to

n(n+1)(2n+1)/6. Hence it would be of order of O(n^3)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!