Time Complexity for loop

十年热恋 提交于 2019-12-11 06:56:49

问题


I was trying to find the time complexity for a for loop. below is loop detail.

for(int i=N;i>1;i=i/2)
{
   for(int k=0;k<i;k++){
     sum++;
   }
}

Below is any find for the problem. Please correct me if i am going worng.

Inner loop will be exceute N+N/2+N/4+N/8....

so tn=ar^(n-1). So replacing Tn=1, a=N and r=1/2

1=N(1/2)^(n-1)

therefore

1/2N=(1/2)^n

So sum of inner loop is a GP. Sn=a(1-r^n)/(1-r) Replacing a=N,r=1/2, we get

Sn=N(1-(1/2N))/(1-1/2)

therefore Sn=2N-1

I am not sure if complexity is N.

Please help

Thanks.


回答1:


Below is the formal way (Sigma Notation) to infer the order of growth related to your algorithm (corroborated with experiments, using C's MinGW2.95 compiler).



来源:https://stackoverflow.com/questions/22413458/time-complexity-for-loop

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