What is the time complexity of following function fun()?

`int` `fun(` `int` `n) ` `{ ` ` ` `for` `(` `int` `i = 1; i <= n; i++) ` ` ` `{ ` ` ` `for` `(` `int` `j = 1; j < n; j += i) ` ` ` `{ ` ` ` `// Some O(1) task ` ` ` `} ` ` ` `} ` `} ` |

*chevron_right*

*filter_none*

For i = 1, the inner loop is executed n times.

For i = 2, the inner loop is executed approximately n/2 times.

For i = 3, the inner loop is executed approximately n/3 times.

For i = 4, the inner loop is executed approximately n/4 times.

…………………………………………………….

…………………………………………………….

For i = n, the inner loop is executed approximately n/n times.

So the total time complexity of the above algorithm is (n + n/2 + n/3 + … + n/n)

Which becomes n * (1/1 + 1/2 + 1/3 + … + 1/n)

The important thing about series (1/1 + 1/2 + 1/3 + … + 1/n) is, it is equal to Θ(Logn) (See this for reference). So the time complexity of the above code is Θ(nLogn).

As a side note, the sum of infinite harmonic series is counterintuitive as the series diverges. The value of is ∞. This is unlike geometric series as geometric series with ratio less than 1 converges.

**Reference:**

http://en.wikipedia.org/wiki/Harmonic_series_%28mathematics%29#Rate_of_divergence

http://staff.ustc.edu.cn/~csli/graduate/algorithms/book6/chap03.htm

This article is contributed by **Rahul**. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready.

## Recommended Posts:

- A Time Complexity Question
- Time Complexity of building a heap
- Time Complexity where loop variable is incremented by 1, 2, 3, 4 ..
- Time Complexity of a Loop when Loop variable “Expands or Shrinks” exponentially
- Time complexity of recursive Fibonacci program
- Practice Questions on Time Complexity Analysis
- Time Complexity Analysis | Tower Of Hanoi (Recursion)
- Python Code for time Complexity plot of Heap Sort
- C program for Time Complexity plot of Bubble, Insertion and Selection Sort using Gnuplot
- Time Complexity of Loop with Powers
- Understanding Time Complexity with Simple Examples
- What does 'Space Complexity' mean?
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Knowing the complexity in competitive programming
- Cyclomatic Complexity
- Complexity Analysis of Binary Search
- Complexity analysis of various operations of Binary Min Heap
- Time taken by Loop unrolling vs Normal loop
- Measure execution time with high precision in C/C++
- Microsoft Interview experience for full time position of software engineer at Microsoft Ireland Research