Daa Assignment
Daa Assignment
Here, a=2na = 2na=2n, b=2b = 2b=2, and there is an exponential factor nnn^nnn.
This doesn't fit the basic form of the Master Theorem because of the term nnn^nnn, and
its complexity is exponential.
Time complexity is O(nn)O(n^n)O(nn).
Here, a=2a = 2a=2, b=2b = 2b=2, and the additional term nlognn \log nnlogn complicates
things.
Using a modified form of the Master Theorem, the time complexity is O(nlog2n)O(n \
log^2 n)O(nlog2n).
Here, a=3a = 3a=3, b=3b = 3b=3, and the non-recursive term is n\sqrt{n}n.
Using the Master Theorem, this falls under case 1, where logba=1\log_b a = 1logba=1
and d=1/2d = 1/2d=1/2.
Time complexity is O(n)O(n)O(n).
This recurrence doesn't fit the exact form of the Master Theorem, but based on analysis:
Time complexity is O(log2n)O(\log^2 n)O(log2n).
The function isBST recursively checks each node and its children to ensure it follows the
BST property.
Time complexity: Since it checks each node exactly once, it runs in O(n)O(n)O(n), where
nnn is the number of nodes in the tree.
This recurrence fits the Master Theorem, where a=1a = 1a=1, b=3b = 3b=3, and d=1d =
1d=1 (for the O(n)O(n)O(n) term).
Time complexity is O(n)O(n)O(n).
a)
cpp
Copy code
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j > 0; j /= 2) {
sum++;
}
}
Outer loop runs nnn times. The inner loop runs in O(logi)O(\log i)O(logi) time.
Total complexity: O(nlogn)O(n \log n)O(nlogn).
b)
cpp
Copy code
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
for (int k = j; k < n; k += j) {
sum++;
}
}
}
The outer loop runs nnn times. The second loop runs approximately O(n)O(n)O(n) times,
but the third loop has a decreasing step k+=jk += jk+=j, making it logarithmic in terms of
jjj.
Time complexity: O(n2logn)O(n^2 \log n)O(n2logn).
c)
cpp
Copy code
k = m = 0;
for(i = 1; i < n; i *= 2) {
k++;
}
for(j = 0; j < k * k; j *= 2) {
m++;
}
d)
cpp
Copy code
i = n, tot = 0;
while (i > 1) {
tot += i;
i = i / 2;
}
e)
cpp
Copy code
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; j++) {
for(int k = 0; k < 10; k++) {
cout << "bawa" << endl;
}
}
}
The outer two loops run O(n2)O(n^2)O(n2), and the inner loop runs a constant 10 times.
Time complexity: O(n2)O(n^2)O(n2).
f)
cpp
Copy code
void function(int n) {
if (n < s) {
cout << n << endl;
} else {
for (int i = 0; i < n; i = i / k) {
cout << i << endl;
}
}
}
The first part (when n <s) is constant, but in the else part, the loop reduces i by dividing
by k, leading to a logarithmic runtime.
Time complexity: Minimum O(1) Maximum O(log n)