Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

What is the time complexity of the following piece of code? Check all that apply: function unknown ( int n ) { int i ,

What is the time complexity of the following piece of code? Check all that apply:
function unknown (int n){
int i, j;
int sum =0;
for (i =1; i <= n; i *=2){
for (j =0; j < i; j++){
sum += j;
}
}
return sum;
}
Group of answer choices
\Theta (n)
o(logn)
\Omega (logn)
\Theta (n^2)
O(n^2*logn)
o(n)
\omega (logn)
\omega (n)
O(n*logn)
O(logn)
\Theta (n^2*logn)
O(n^2)
\Omega (n^2*logn)
\Theta (n*logn)
o(n*logn)
\Theta (logn)
\Omega (n^2)
\omega (n*logn)
\Omega (n*logn)
\Omega (n)
O(n)
Heres the best way to solve it.
Expert-verified
Share
(0)
//lets analyze the given code to find time complexity
int i, j;//runs in constant time so : O(1)
int sum =0;//runs in constant time so : O(1)
for (i =1; i <= n; i *=2)//runs for i=1 to n, each time i is multiplied by 2, so runs for 2^k = n, k=logn times//base is 2
{
for (j =0; j < i; j++)//runs for i times
{
//possible value of i: 1,2^1,2^2,2^3,...,2^k
sum += j;//so runs for : 1+2^1+2^2+2^3+...+2^k =2^(k+1)-1=(2*k)*2-1=2*logn -1
}
}
return sum;//runs in constant time so : O(1)
}
overall run time : 1+1+2*logn-1+1=2*logn+2= theta(logn)
note: theta(logn) means both bigOh(logn) and bigOmega(logn

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions