Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Give the Big-Oh for the running time of each code fragment. a. double power( dou

ID: 3590851 • Letter: G

Question

Give the Big-Oh for the running time of each code fragment.

a.
double power( double x, int n ) {
double result = 1.0;
for( int i = 0; i < n; i++ )
result *= x;
return result;
}


b.
bool hasTwoTrueValues( bool array [], int n ) {
for( int i = 0; i < n; i++ )
for( int j = i + 1; j < n; j++ )
if( array[ i ] && array[ j ] )
return true;
return false;
}


c.
bool hasTwoTrueValues( bool array [], int n ) {
int count = 0;
for( int i = 0; i < n; i++ )
if( array[ i ] )
count++;
return count >= 2;
}


d.
bool hasTwoTrueValues( bool array [], int n ) {
for( int i = 0; i < n; i++ )
if( array[ i ] )
for( int j = i + 1; j < n; j++ )
if( array[ j ] )
return true;
return false;
}

Explanation / Answer

a)

The for loop n times.

Hence, Time Complexity = O(n)

b)

When ,

i = 0 ,    inner for loop runs n - 1 times

i = 1 ,   inner for loop runs n - 2 times

.

.

.

i = n - 1 , inner for loop runs 0 times

Hence, number of times both loops run = 0 + 1 + 2 + ... + (n-1) = 1 + 2 + ... + (n-1)

           = ( n - 1 ) ( n - 1 + 1 ) ( 2 * ( n - 1 ) + 1 ) / 6

( using sum of squares of n natural numbers = n (n + 1)(2n + 1) / 6 )

Hence, time complexity = O(n ^ 2)  

c)

The for loop n times.

Hence, Time Complexity = O(n)

d)

When ,

i = 0 ,    inner for loop runs n - 1 times

i = 1 ,   inner for loop runs n - 2 times

.

.

.

i = n - 1 , inner for loop runs 0 times

Hence, number of times both loops run = 0 + 1 + 2 + ... + (n-1) = 1 + 2 + ... + (n-1)

           = ( n - 1 ) ( n - 1 + 1 ) ( 2 * ( n - 1 ) + 1 ) / 6

( using sum of squares of n natural numbers = n (n + 1)(2n + 1) / 6 )

Hence, time complexity = O(n ^ 2)  

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote