I am just learning about time complexity, here is piece of code I've written
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++)
{
// Spread Peace
}
Clearly the above one is of O(N^2) complexity and its seems (for N == 1e6
) to run forever.
Here is second piece of code
for (int i = 1; i <= N; i++)
for (int j = i; j <= N; j++)
{
// Money is Everything
}
the above one is also O(N^2) - N*(N+1)/2 complexity is also running forever, but this code:
for (int i = 1; i <= N; i++)
for (int j = i; j <= N; j += i)
{
// Be my GirlFriend
}
just executes within a sec., I am not able to derive its time complexity why this so fast? What's is the estimation for N == 1e6
?