Search⌘ K

Solution: Big (O) of Nested Loop With Subtraction

Explore how to analyze and compute the time complexity of nested loops involving subtraction in JavaScript. Learn to break down loop executions line by line and determine the Big O notation, helping you evaluate and optimize algorithm efficiency.

We'll cover the following...

Solution #

Node.js
const n = 10;
const pie = 3.14;
let sum = 0;
for (var i = n; i >= 1; i -= 3) {
console.log(pie);
for (var j = n; j >= 0; j--) {
sum = sum + 1;
}
}
console.log(sum);

On line 6 in the outer loop, var i=n; runs once, i>=1; gets executed n3+1\frac{n}{3}+1 times and i-=3 executed n3\frac{n}{3} times. In the inner loop, var j=n; gets executed n3\frac{n}{3} times in total, j>=0; executes n3× (n+2)\frac{n}{3} \times \ (n+2) times and j-- gets executed n3× (n+1)\frac{n}{3} \times \ (n+1) ...