What is the complexity of each of these loops? If an array is
mentioned, they use arr of
size N, and possibly arr2 of
and M. Consider upper and lower bounds.
-
for(int i = 0; i < arr.size(); ++i)
sum += arr[i];
-
for(int i = 0; i < arr.size(); i += 2)
sum += arr[i];
-
for(int i = 1; i <= arr.size(); i *= 2)
sum += arr[i];
-
int a = 0, b = arr.size()-1;
while(a < b) {
int p = (a + b)/2;
if(x < arr[p])
b = p-1;
else if(x > arr[p])
a = p+1;
else
break;
}
-
for(int i = 0; i < arr.size(); i++)
for(int j = 0; j < arr.size(); j++)
sum += arr[i]*arr[j];
-
for(int i = 0; i < arr.size(); i++)
for(int j = 1; j <= arr.size(); j *= 2)
sum += arr[i]*arr[j];
-
for(int i = 1; i <= arr.size(); i++)
for(int j = i; j < arr.size(); j++)
sum += arr[i]*arr[j];
-
for(int i = 0; i < arr.size(); i++)
for(int j = i; j < arr.size(); j += i+1)
sum += arr[i]*arr[j];
-
for(int i = 0; i < arr.size(); ++i) arr[i] = 0;
while(true) {
for(int i = 0; i < arr.size(); ++i) print arr[i];
int j = arr.size() - 1
for( ; j >= 0 && arr[j] == 9; --j)
arr[j] = 0;
if(j < 0)
break;
else
++arr[j];
}
Think about what the output looks like. That should give you
the number of iterations for the outer loop.
- For the last two, b and e are the input
values to the computation. Consider e to be the size of the
problem, and find a complexity as a function of e.
p = 1;
for(int i = 0; i < e; ++i)
p *= b;
-
p = 1;
while(e > 0) {
if(e % 2 == 0) {
p *= p;
e /= 2;
} else {
p *= b;
--e;
}
}
- Zheng's Problem