int sum = 0; for(int i = 1; i < n; i++) { for(int j = 1; j < i * i; j++) { if(j % i == 0) { for(int k = 0; k < j; k++) { sum++; } } } }
I don't understand how when j = i, 2i, 3i... the last for
loop runs n times. I guess I just don't understand how we came to that conclusion based on the if
statement.
Edit: I know how to compute the complexity for all the loops except for why the last loop executes i times based on the mod operator... I just don't see how it's i. Basically, why can't j % i go up to i * i rather than i?
Linear time complexity O(n) means that the algorithms take proportionally longer to complete as the input grows. Examples of linear time algorithms: Get the max/min value in an array. Find a given element in a collection. Print all the values in a list.
O(1) — Constant Time Constant time algorithms will always take same amount of time to be executed. The execution time of these algorithm is independent of the size of the input. A good example of O(1) time is accessing a value with an array index.
For example, Selection sort and Insertion Sort have O(n2) time complexity. 4) O(Logn) Time Complexity of a loop is considered as O(Logn) if the loop variables are divided/multiplied by a constant amount. And also for recursive call in recursive function the Time Complexity is considered as O(Logn).
Big O notation is used in Computer Science to describe the performance or complexity of an algorithm. Big O specifically describes the worst-case scenario, and can be used to describe the execution time required or the space used (e.g. in memory or on disk) by an algorithm.
Let's label the loops A, B and C:
int sum = 0; // loop A for(int i = 1; i < n; i++) { // loop B for(int j = 1; j < i * i; j++) { if(j % i == 0) { // loop C for(int k = 0; k < j; k++) { sum++; } } } }
j % i == 0
is evaluated, which takes O(1) time.Multiplying all of this together, we get O(n × i2 × (1 + i)) = O(n × i3). Since i is on average O(n), this is O(n4).
The tricky part of this is saying that the if
condition is only true 1/i of the time:
Basically, why can't j % i go up to i * i rather than i?
In fact, j
does go up to j < i * i
, not just up to j < i
. But the condition j % i == 0
is true if and only if j
is a multiple of i
.
The multiples of i
within the range are i
, 2*i
, 3*i
, ..., (i-1) * i
. There are i - 1
of these, so loop C is reached i - 1
times despite loop B iterating i * i - 1
times.
n
iterations.n*n
iterations. Imagine the case when i=n
, then j=n*n
.n
iterations because it's executed only i
times, where i
is bounded to n
in the worst case.Thus, the code complexity is O(n×n×n×n).
I hope this helps you understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With