Search⌘ K
AI Features

Solution Review: Big (O) of Nested Loop with Addition

Explore how to analyze the time complexity of nested loops with addition by breaking down loop executions line-by-line. Learn to calculate and simplify running time expressions and determine the Big O notation for code efficiency.

We'll cover the following...

Solution

C#
namespace Chapter_1
{
class Challenge_1
{
static void Main(string[] args)
{
int n = 10;
int sum = 0;
float pie = 3.14F;
for (int i = 0; i < n; i += 3) // O(n/3)
{
Console.WriteLine(pie); // O(n/3)
for (int j = 0; j < n; j += 2) // O((n/3)*(n/2))
{
sum += 1; // O((n/3)*(n/2))
Console.WriteLine(sum); // O((n/3)*(n/2))
}
}
}
}
}

On line 11 in the outer loop, int i=0; runs once. i<n; gets executed n3+1\frac{n}{3}+1 ...