0
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.

crucialoil
  • 381
  • 1
  • 5
  • 17

3 Answers3

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).

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • Hi, could you please show me step by step how to compute the complexity? I saw on some books the calculate by using T(n) sth. But I have no idea how it works. Please help me. – crucialoil Mar 08 '15 at 15:50
0

For this program , complexity is O(n)

0

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.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • Hi, could you please show me step by step how to compute the complexity? I saw on some books the calculate by using T(n) sth. But I have no idea how it works. Please help me. – crucialoil Mar 08 '15 at 15:50
  • 1
    @LucasVinhTran: In the general case, a loop iterates N-1 times. Each time a constant number of operations, each of constant complexity, such as addition and indexing, is performed. I.e. the loop body has constant complexity. Since it's performed on the order of N times, it has complexity O(N). That's without going into the finer points of the notation, where practice in online forums (text typed via keyboard) is somewhat at odds with the notation that mathematically bent computer scientists have chosen (text written with pencil or chalk). You can find more information e.g. in Wikipedia. – Cheers and hth. - Alf Mar 08 '15 at 17:39
  • @Jack: This function is not using memoization. A result is computed for every call. – Cheers and hth. - Alf Mar 08 '15 at 17:43