I am trying to calculate the time complexity of the below code snippet
def func()
{
for(i=1; i<=n; i++)
{
for(j=1; j<=n; j=j+i)
{
print("hello")
}
}
}
This is how I calculate -
The first for loop for variable i
executes for n
times. The inner for loop is dependent on i
, the variable j
is incremented as follows: 1 + 2 + 3 + ... + k
and a time would come when it becomes larger than n
. So 1 + 2 + 3 + ... + k
= Sum of k
natural numbers = k(k + 1)/2
.
k(k + 1)/2 = n
So for inner for loop time complexity is O(n^1/2)
The time complexity of entire function = time complexity of outer for * time complexity of inner for = O(n * n^1/2)
But actually, it's O(nlogn)
. Can anyone please explain how and what is wrong with the approach I have used?