Homework 3: Running Times
Due: Friday, March 9, 8:59:59pm
Instructions: In each of the questions below, you are given a program fragment. Your task is to estimate the running time of each program fragment in terms of n. You should assume that the value of n is defined elsewhere in the program. The running time that you report should be the tightest upper bound you can find. Don't just say everything is O(2n), because although correct, it is not precise enough. Upper bounds that are too big will receive deductions during grading.
For each question:
- State an upper bound on the running time of the program fragment using O( ) notation.
- Briefly justify your upper bound.
What to turn in: Type your response in a single text file called
hw3.txt and place it in your
hw3 submission directory on GL. Please make sure you number your responses by question. Remember that flex days do not apply to homework assignments. Type n^2 for n
2
Question 1
x = n ;
while ( 1 < x ) {
x = x / 2 ;
}
Question 2
t = 1;
for (int i = 0; i < n; i++) {
t = t++;
}
while ( t > 1 ) {
t = t / 2;
}
Question 3
void doIt(int x) {
while ( 1 < x ) {
x = x / 2 ;
}
}
// ...somewhere in main()...
for(int i = 0; i < n; i++){
doIt(i);
}
Question 4
int x = n;
int count = 0;
while ( x > 1 ) {
for (int i = 0; i < x; i++) {
count++;
}
x = x / 2;
}
Question 5
t = n + 5;
while ( t < n ) { // not a typo!
t = t + 5;
}
Question 6
For this question, report the runtime of both the
loopIt() function and the overall runtime of the snippet including the calls to
loopIt().
int loopIt(int x) {
int count = 0;
for (int i = 0; i < x; i++) {
count++;
}
return count;
}
// ...somewhere in main()...
int sum = n ;
sum = loopIt(2) + sum;
sum = loopIt(4) + sum;
Question 7
int sum = 0;
int i = 1;
while (sum <= n) {
sum = sum + i;
i++;
}
Question 8
for (int i = 0 ; i < n ; i++) {
int j = 2 * i ;
while (j < n) {
j = j + 2 ;
}
}
Question 9
int sum = 0;
for (int j = n; j > 0; j /= 2) {
for (int k = 0; k < j; k++) {
sum += 1;
}
}