For each sample of code given below, indicate precisely how many times each line
ID: 3858608 • Letter: F
Question
For each sample of code given below, indicate precisely how many times each line runs in terms of the variables given. Sometimes, you will be able to give an exact integral answer, like "10". Other times, your answer will be in terms of n or some other variable or combination of variables. If the snippet of code is a method, you do not have to write the number of times the top line (the method declaration itself) is executed.
Q3.
for (int i=0; i<n; i++) {
for (int j=n; j>=i; j--)
cout << i << “,” << j <<endl;
}
Q4.
for (int i=0; i<n; i++) { //assume n is divisible by 2 => n = 2*k
for (j=n/2; j>i; j--)
sum = i+j;
}
Q5.
//matrix multiplication of A[m][n] and B[n][p]. The product is saved into C[m][p].
void mult_matricies( double A[][n], double B[][p], double C[][p], int m, int n , int p ){
for (int i=0; i<m; i++) {
for (int j=0; j<p; j++){
C[i][j] = 0;
for ( int k=0; k<n; k++) {
C[i][j] += A[i][k] * B[k][j];
}//for-k
}//for-j
}//for-i
}
Explanation / Answer
Q3.
for (int i=0; i<n; i++) { // O(n) times
for (int j=n; j>=i; j--) // O(n) times
cout << i << “,” << j <<endl; // O(n*n) times => total time complexity
}
Q4.
for (int i=0; i<n; i++) { //assume n is divisible by 2 => n = 2*k // O(n) times => total time complexity
for (j=n/2; j>i; j--) // O(1) time
sum = i+j; => this line never gets executed.
}
Q5.
//matrix multiplication of A[m][n] and B[n][p]. The product is saved into C[m][p].
void mult_matricies( double A[][n], double B[][p], double C[][p], int m, int n , int p ){
for (int i=0; i<m; i++) { // O(m) times
for (int j=0; j<p; j++){ // O(p) times
C[i][j] = 0; // O(m*p) times
for ( int k=0; k<n; k++) { // O(n) times
C[i][j] += A[i][k] * B[k][j]; // O(n*m*p) times => total time complexity
}//for-k
}//for-j
}//for-i
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.