Search⌘ K
AI Features

Solution: Nested Loop with Multiplication (Advanced)

Explore the detailed time complexity analysis of a nested loop with multiplication in Java. Learn to calculate Big O notation involving logarithmic factors and factorial terms, helping you understand and optimize algorithm performance in coding interviews.

Given Code

Java
class NestedLoop {
public static void main(String[] args) {
int n = 10; //O(1)
int sum = 0; //O(1)
double pie = 3.14; //O(1)
for (int var = 0; var < n; var++) { //O(n)
int j = 1; //O(n)
System.out.println("Pie: " + pie); //O(n)
while(j < var) { // O((n) * (log2 var))
sum += 1; // O((n) * (log2 var))
j *= 2; // O((n) * (log2 var))
}
} //end of for loop
System.out.println("Sum: " + sum); //O(1)
} //end of main
} //end of class

Solution Breakdown

In the main function, the outer loop is O(n)O(n) ...