1
$\begingroup$

This question already has an answer here:

Suppose the function $f(n)$ is defined as the number of $\ast$ printed in the following code

for(int i = 0; i<n; i++) {
    for(int j = i; j<n; j++) {
        for(int k = j + 200; k<2n; k++) {
            for( int r = k^2; r<n; r++) {
                print(*);
            }
        }
    }
}

I suspect the answer is $\Theta(n^{2.5})$, by running the code at $n=5000$ and $n=50000$, but I do not have a rigid proof.

Can anyone enlighten me? Thank you!

$\endgroup$

marked as duplicate by David Richerby, Evil, Raphael algorithms Aug 28 '18 at 18:37

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\begingroup$ What have you tried? Where did you get stuck? We do not want to just hand you the solution; we want you to gain understanding. However, as it is we do not know what your underlying problem is, so we can not begin to help. See here for tips on asking questions about exercise problems. If you are uncertain how to improve your question, why not ask around in Computer Science Chat? $\endgroup$ – Raphael Aug 28 '18 at 18:38
1
$\begingroup$

First, note that we print a * for every tuple $(i,j,k,r)$ such that $0 \leq i \leq j \leq k-200 \leq \sqrt{r}-200\leq \sqrt{n}-200$

For every $i$ and $j$ there are at most $(\sqrt{n}-200)$ options, for $k$ it is $\sqrt{n}$ and for $r$ it is $n$. Thus the upper bound for the number of * is $(\sqrt{n}-200)\cdot (\sqrt{n}-200) \cdot \sqrt{n} \cdot n\in O(n^{2.5})$.

To compute the lower bound, we can take $i$'s in the range between $0$ and $\frac{\sqrt{0.5n}-200}{2}$, $j's$ between $\frac{\sqrt{0.5n}-200}{2}+1$ and $\sqrt{0.5n}$, $k$'s between $\sqrt{0.5n}+1$ and $\sqrt{0.75n}$, and finally, $r's$ between $0.75n+1$ to $n$. Thus the number of options for a tuple $(i,j,k,r)$ is more than $(\frac{\sqrt{0.5n}-200}{2})^2 \cdot (\sqrt{0.75n}-\sqrt{0.5n})\cdot 0.25n \in \Omega(n^{2.5})$.

Thus the answer is $\Theta(n^{2.5})$

$\endgroup$
  • 1
    $\begingroup$ Hi, and thanks for taking the time to write up an answer! Note that we have a reference question that explains in detail how to approach problems such as the OP's, so you may want to invest your energy on less routine questions in the future. $\endgroup$ – Raphael Aug 28 '18 at 18:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.