What is the time complexity of the code below?

☆樱花仙子☆ 提交于 2021-01-27 18:30:23

问题


sum =0;

            for (int i=1; i<n; i++) {

              for (int j=1; j< n/i; j++) {

                sum = sum +j;

              }

            }

In the above outer loop , The variable i runs from 1 to n, thus making complexity of outer loop as O(n). This explains the n part of O(n logn) complexity.

But for the outer part when we see then j runs from 1 to n/i, meaning whenever i is 1 , the complexity is n so i guess the inner time complexity should also be O(n).

Making the total time Complexity as O(n*n)=O(n^2).


回答1:


This is what you can do using Sigma notation:

With H_{n-1} is the harmonic function:

Finding Big O of the Harmonic Series



来源:https://stackoverflow.com/questions/39846590/what-is-the-time-complexity-of-the-code-below

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!