| Example of for loop:
/* The purpose of the following program is to calculate 1 + 8 + 27 + 64 + 125 + .... n^3 (Sum of cube of each integer from 1 to n)*/ #include<iostream.h>
void main()
cout<<"We are going to
calculate \n"
int Sum(int n)
/* Total Time: 1+(1+n+1+n)+4n+1=6n+4=O(n)
*/
Exercise: Do the problem similar to above:
Find the sum of squares of the numbers.
|
There exists 7 such that 0 < 6n+4 < 7n whenever n > 4. So, 6n+4 = O(n) |
for(i=0; i<n; i++) // count 1+(n+1)+n = 2n + 2/* Total time: (2n+2) + n*(2n+2) + n*n = 3n2+4n+2 = O(n2) */
for(j=0; j<n; j++) // count n*(2n+2)
k++; // count 1 unit each and repeated n*n times
for(i=0; i<n; i++)/* Total time: O(n) + O(n2) = O(n2) */
A[i] = 0; //The first loop takes O(n)
for(i=0; i<n; i++) //The second loop is a nested loop.
for(j=0; j<n; j++) //It takes O(n2)
A[i]+=A[j] + i + j;
if(condition)Total time = time for checking condition + the maximum time of (S1, S2).
S1
else
S2
long factorial(int n)
{
if(n <= 1) //Test part time = 1
return 1; // T(1) = 2
else //more time on else part
return n * factorial(n-1); //"return" takes 1 step, "*" takes 1 step
}
/* T(n) = 1 + 2 + T(n-1) = T(n-1)+ 3
= T(n-2)+ 3 + 3
= T(n-3)+ 3 + 3 + 3
...
= T(n-(n-1)) + (n-1)*3
= T(1) + (n-1)*3
= 2 + 3n-3
=O(n) */
void print(int x)
{
if (x < 4)
cout<<x;
else
{
print(x/4);
cout<<x%4;
}
cout<<endl;
}
/* T(n)=1+T(n/4)+2 = O(log n) */
long fib(int n)
{
if(n <= 1)
return 1;
else
return fib(n-1) + fib(n-2);
}
/* T(n) = T(n-1) + T(n-2) + 2 and T(0) = T(1) = 2
By Mathematical Induction, (3/2)n < T(n) < (5/3)n
Note: check the above with Fibonacci Numbers
It grows exponentially. */