...

/

Solution Review: Nested Loop with Multiplication (Pro)

Solution Review: Nested Loop with Multiplication (Pro)

This review provides a detailed analysis of the different ways to solve the "Nested Loop with Multiplication (Pro)" challenge.

Solution #

Press + to interact
Rust 1.57.0
fn main(){
let n = 10;
let mut sum = 0;
let mut j = 1;
let pie = 3.14;
for i in 0..n{ // O(n)
println!("{}",pie); // O(n)
while j<i{ // O(log(n))
sum += 1; // O(log(n))
j *= 2; // O(log(n))
}
}
println!("{}",sum);
}

The outer loop in the main function has “n” iterations as it iterates on i from 0 to n-1. If the condition j < i is true, the inner loop is entered. However, j is doubled immediately. Note that j is not reset to 1 in the code, since the j is immediately doubled. Therefore, the inner while loop will run O(log2(n))O(log_2(n)) times for all the iterations of the outer loop.

Note: Inner while loop will run (at most) once for each iteration of the outer loop.

Statement Number of Executions
let n = 10;
1
let mut sum = 0;
1
let mut j = 1;
1
let pie = 3.14;
1
for i in 0..n
nn
...
Access this course and 1400+ top-rated courses and projects.