What is the time complexity in Big-O notation of the given piece of code?

627 Views Asked by At

Before asking this question, I read through my textbook and an online website to understand Big-O notation, and I am still having a difficult time understanding how to calculate the time complexity in Big-O notation.

How would I go about calculating the time complexity of the following piece of code?

    //Headers, Syntax, and other information are already pre-declared.
    int n, sum = 0;
    cin >> n;
    for (int i = 0; i < n; ++i)
        {
           for (int j = 1; j < n³; j = (3 * j))
               {
                   ++sum;
               }
        }
1

There are 1 best solutions below

0
On BEST ANSWER

It depends on your undefined variable n3:

  • If this means $3n$ or even $n^3$ the inner loop runs in $\log(n)$ time because it computes the exponential function $3^j.\;$ Therefore the overall complexity will be $O(n\log n)$.

  • If n3 means $3^n$ the count for the inner loop is $\approx n$ and and you have $O(n^2)$-