Lecture 04 Calculating Time Complexity
Lecture 04 Calculating Time Complexity
c*n = cn = O(n)
Calculating Time
Complexity
• Nested Loop - Multiplication
for(i=1;i<=n;i++) //n
{ multiply
for(j=1;j<=n;j++) //n n x n = n2
{
a=a+b; //constant c x n2
}
}
c*n*n = cn2 = O(n2)
Calculating Time
Complexity
• Consecutive Statements - Addition
a = a + b //c1
{
for(i=1;i<=n;i++) //n
{ X c2n addition
x = x + y; //c2 c1 + c2n+c3n
}
for(j=1;j<=n;j++) //n
{ X c3n
c = c + d; //c3
}
}
c1 + c2n+c3n = O(n)
Calculating Time
Complexity
• if-else Statements
if (cond.)
{
for (i=1;i<=n;i++)
{
O(n)
a = a + b;
}
} Worst Case
else O(n) + O(n2) O(n2)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++) O(n2)
{
c = c + d;
}
}
}
Calculating Time
Complexity
• Logarithmic Complexity log(n):
• Represented in Big O notation as O(log
n),
• When an algorithm has O(log n) running
time, it means that:
• as the input size grows, the number of operations
grows very slowly.
• Example: binary search.
Logarithmic Example
• Example 1: loga b
• Task: We have a number N which has an initial
value of 16 and the task is to reduce the given
number to 1 by repeated division of 2.
Approach:
• Initialize a variable number_of_operation with a
value 0 .
• Run a for loop from N till 1.
• In each iteration reduce the value of N to half.
• Increment the number_of_operation variable by one.
• Return the number_of_operation variable.
// C++ code for reducing a number to its
logarithm
#include <bits/stdc++.h>
using namespace std;
int main()
{
int N = 16;
int number_of_operations = 0;
Algorithm: SUM(A, B)
Step 1 - START
Step 2 - C ← A + B + 10
Step 3 - Stop
• Here we have three variables A, B, and C
• One constant 10.
• Hence S(P) = 1 + 3. Now, space depends on data types of given
variables and constant types and it will be multiplied accordingly.