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

前端 未结 2 1459
既然无缘
既然无缘 2021-01-24 04:32
function alg1(n)
1 a=0
2 for o=1 to n do
3     for t=1 to o do
4         for k=t to o+t do
5         a=a+1
6 return(a)

If anyone could guide me to how

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-24 04:48

    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)

提交回复
热议问题