Solution: Big O of a Nested Loop with Multiplication
Learn to analyze the time complexity of a nested loop with multiplication.
We'll cover the following...
Solution #
Press + to interact
int n = 10; // Can be anythingint sum = 0;double pie = 3.14;int i = 1;while (i < n){System.Console.WriteLine(pie);for (int j = 0; j < i; j++){sum += 1;}i *= 2;}System.Console.WriteLine(sum);
Explanation
The answer is . Have a look at the slides below for an in-depth explanation of the answer.
Note: In the slides below, “RTC” is an abbreviation of running time complexity.
Press + to interact
1 / 16
Time complexity
The above slides give a detailed, step-by-step analysis of the code. Here, we provide a more summarized version.
The outer loop here runs times. In the first iteration of the outer loop, the body of the inner loop runs once. In the second iteration, it runs twice, and so on. The number of executions of the body of the inner loop increases in powers of . So, if is the number of iterations of the outer loop, the body of the inner loop runs a total of ...