How does the if-statement of this code affect the time complexity of this code?
Based off of this question: Runtime analysis, the for loop in the if statement would run n*n times. But in this code, j outpaces i so that once the second loop is run j = i^2
. What does this make the time complexity of the third for loop then? I understand that the first for loop runs n times, the second runs n^2
times, and the third runs n^2
times for a certain amount of times when triggered. So the complexity would be given by n*n^2(xn^2)
for which n
is the number of times the if statement is true. The complexity is not simply O(n^6)
because the if-statement is not true n times right?
int n;
int sum;
for (int i = 1; i < n; i++)
{
for (int j = 0; j < i*i; j++)
{
if (j % i == 0)
{
for (int k = 0; k < j; k++)
{
sum++;
}
}
}
}
The if
condition will be true when j
is a multiple of i
; this happens i
times as j
goes from 0 to i * i
, so the third for
loop runs only i
times. The overall complexity is O(n^4).
for (int i = 1; i < n; i++)
{
for (int j = 0; j < i*i; j++) // Runs O(n) times
{
if (j % i == 0) // Runs O(n) × O(n^2) = O(n^3) times
{
for (int k = 0; k < j; k++) // Runs O(n) × O(n) = O(n^2) times
{
sum++; // Runs O(n^2) × O(n^2) = O(n^4) times
}
}
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments