Solution: Big (O) of Nested Loop with Addition
This review provides a detailed analysis of the time complexity of the Nested Loop with Addition problem!
We'll cover the following...
Solution: #
Press + to interact
int main(){int n = 10;int sum = 0;float pie = 3.14;for (int i=1; i<n; i+=3){ // O(n/3)cout << pie << endl; // O(n/3)for (int j=1; j<n; j+=2){ // O((n/3)*(n/2))sum += 1; // O((n/3)*(n/2))cout << sum << endl; // O((n/3)*(n/2))}}}
On line 6 in the outer loop, int i=1;
runs once, i<n;
gets executed times and i+=3
executed times. In the inner loop, int j=1;
gets executed times in total. j<n;
executes times and j+=2
gets executed times. Study the following table for a more detailed line-by-line analysis of the calculation of time complexity.
int n = 10; |
|
int sum = 0; |
|
float pie = 3.14; |
|
int i=1; |
|
i<n; |