嵌套的for循环的运行时复杂性

时间:2018-10-12 00:29:18

标签: algorithm time-complexity big-o complexity-theory nested-loops

for(a = c; a > 0; a/=2) 
    for(b=0; b < 2*a; b++)

我已经得出结论,这是O(nlogn)运行时,但是我不确定。 我的逻辑是,最外层的for循环每次运行都会被除以2,然后运行logn倍,然后最内层的for循环运行一半的数字的2倍。因此它运行了n次。

1 个答案:

答案 0 :(得分:0)

let req = this.generatePostRequest(apiParams);
req.write(json);    
req.end();

输出

#include <iostream>

int main() {

    int c = 16;

    for(int a = c; a > 0; a/=2) {

        for(int b =0; b < 2*a; b++)
            std::cout << "*";

        std::cout << std::endl;
    }
}
  • 在第一个内部循环中,您看到b从0到2​​ * a
  • 在第二个内部循环中,您看到b从0到2​​ *(a / 2)
  • 在第三个内部循环中,您看到b从0到2​​ *(a / 4)

对这些求和:2a + a + a / 2 + ... + 1 = 2a -1 \ in O(n),因为输入大小。