

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Six C++ code segments that use for loops, and the reader is required to evaluate the asymptotic complexity of each segment. solutions for each segment. The document assumes that each cout statement has a constant run time of O(1). useful for computer science students who want to learn about asymptotic complexity in C++ code segments.
Typology: Exercises
1 / 2
This page cannot be seen from the preview
Don't miss anything!


For each of the following C++ code segments using a for loop, you will need to be able to evaluate the asymptotic complexity, we can assume that each cout statement will have a constant run time, i.e. O(1)
Solution: ∑n− 1 i=0 1 =^ O(n)
Solution: ∑n^2 − 1 i=0 1 =^ O(n
Solution: ∑n− 1 i=
( ∑n− 1 j=0 1
∑n− 1 i=0 n^ =^ O(n
Solution: ∑n− 1 i=
( ∑n 2 j=0 1
∑n− 1 i=0 n
(^2) = O(n (^3) )
Solution: Uses Gauss’s formula
∑n i=1 i^ =^
n(n+1) 2 ∑n− 1 i=
( ∑i j=0 1
∑n− 1 i=0 i^ =^
(n−1)(n−1+1) 2 =^
n^2 −n 2 =^ O(n
Solution: This is literally the definition of log 2 n so O(log n)
Solution: This is the definition of log 2 n^2 = 2 log n = O(log n)
Solution: The inner loop runs O(log n) so
∑n− 1 i=0 log^ n^ =^ O(n^ log^ n)
Solution: log 2 1 + log 2 2 + log 2 3 + .. + log 2 (n − 1) = log(n!) =
∑n ∫ (^) n i=1^ log^2 n^ = 1 ln^ xdx^ =^ n^ ln^ n^ −^ n^ −^ (ln 1^ −^ 1) =^ O(n^ log^ n)
Solution: ∑log 2 n i=
( ∑n− 1 i=0 1
∑log 2 n i=0 n^ =^ O(n^ log^ n)
Solution: Geometric Series n + n 2 + n 4 + n 8 + ... + 0 ≈ 2 n = O(n)