此算法的复杂性是什么?

问题描述

我正在学习如何找到算法的复杂性,但我不知道该算法的复杂性是什么。有人可以向我解释如何获得答案吗?

void algorithm(int a,int b) {
    while (a >= b) {
        int x = a - b;
        for (int i = 0; i <= x; i++) {
            std::cout << "complexity of this algorithm?";
        }
        a = x;
    }
}

欢迎任何输入。这是我到目前为止所拥有的:

This is what I have so far

解决方法

a被修改后,您应该将其包含在sum参数中:

(1) x = a - b  // first iteration
(2) x = a - 2b // second iteration
(3) x = a - 3b
...

如果a = k * b,则外循环迭代k次。因此,最终的复杂度是:

(a - b) + (a - 2b) + ... + (a - (k-1) b) = 
(k-1) b + (k-2) b + ... + b = k * (k-1) * b/2

您已经提到 ,时间复杂度为

,

复杂度为(a ^ 2 / b)

正如我在图片中所描述的,您需要将所有“ x”加起来,那么您将获得复杂性。

in summation part for (-b -2b -3b - ... -nb) you can write :
[![enter image description here][1]][1]-b (1+2+...)
so this is -b*(n(n+1)/2)

summation_part_definition_link

enter image description here

最后,如果“ a”和“ b”的顺序相同,则结果为:

O(c)= 0(c是数字)

这意味着复杂度按数字顺序。但是,如果“ a”为高阶,则结果为:

O((a ^ 2)/ b)