Reputation: 540
what would be the time complexity of the following
int i,j,k;
for(i=n/2 ;i<=n ;i++)
{
for(j=1;j<=n/2;j*3)
{
for(k=1;k<=n;k=k*2)
{
pf('vish');
}
}
}
Upvotes: 1
Views: 554
Reputation: 76366
You can solve this by applying a number of simple rules.
Here, for example, note that the internal loops (on j
and i
), for example, don't depend on i
.
for(i=n/2 ;i<=n ;i++)
{
for(j=1;j<=n/2;j*3)
{
for(k=1;k<=n;k=k*2)
If the boundaries are Θ(n), and the increments are fixed additions, the number of iterations is Θ(n). So, for example
for(i=n/2 ;i<=n ;i++)
is performed Θ(n) times.
If the boundaries are Θ(n), and the increments are fixed multiplications, the number of iterations is Θ(log(n)). So, for example
for(j=1;j<=n/2;j*3)
is Θ(log(n)).
A constant function is O(1).
pf('vish');
is O(1).
Combining the above rules, we have an O(1) function being performed Θ(n) Θ(log(n)) Θ(log(n)) times. The complexity is Θ(n log(n)2).
Upvotes: 0
Reputation: 53839
Let's look at how many times each loop is executed:
for(i=n/2 ;i<=n ;i++) // executed O(n) times
{
for(j=1;j<=n/2;j*3) // executed O(log_3(n)) times
{
for(k=1;k<=n;k=k*2) // executed O(log_2(n)) times
{
pf('vish');
}
}
}
Assuming pf
is O(1)
(constant time), the overall complexity is O(n * log(n)^2)
.
Upvotes: 1