Time Complexity of Fibonacci Series

时光怂恿深爱的人放手 提交于 2019-12-12 03:59:17

问题


long int F(int n){
 long int F[n];
 if (n<2) return n;
 else {
      F[0]=0; F[1]=1;
      for (int i=2; i<n+1; i++)
         F[i]=F[i-1]+F[i-2];
      return F[n]; }
 }

Hi guys, can anyone know how to compute the time complexity of the function above? I am studying C++ and I am quite suffering about compute time complexity of a random algorithm. Please help me! Thanks in advance.


回答1:


The code shown relies on a g++ language extension, variable length arrays.

I.e. it's not standard C++.

The code also misdirects a little by using the name F for two different things.

And do note that the code exhibits Undefined Behavior by indexing an array beyond its end.

Apart from that it's trivial.

When the code is corrected, or is viewed as just pseudo-code, doing n-1 operations has complexity O(n).




回答2:


For this program , complexity is O(n)




回答3:


Since the algorithm is using memoization, time and space complexity is linear O(n).

Usually time complexity involves accounting comparison operations on data, which are missing in this case (the only real comparison operation is the bound check), so the linear complexity is give by the F[i-1]+F[i-2] operation.



来源:https://stackoverflow.com/questions/28927851/time-complexity-of-fibonacci-series

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