且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

查找算法的指令数

更新时间:2022-02-25 23:20:35

您已经正确计算出 a 值c> i 内循环的第一个迭代是:

You have correctly calculated that the value of a after the i-th iteration of the inner loop is:

其中 a_j0 a j 次外循环。内循环的停止条件为:

Where a_j0 is the value of a at the start of the j-th outer loop. The stopping condition for the inner loop is:

可以将其解决为二次不等式:

Which can be solved as a quadratic inequality:

因此,内部循环大约为 O(sqrt(a_j0 / b)) a next 起始值满足:

Therefore the inner loop is approximately O(sqrt(a_j0 / b)). The next starting value of a satisfies:

大致缩放为 sqrt(2b * a_j0)。精确地计算时间复杂度将非常繁琐,因此让我们从此处开始应用上述近似值:

Scaling roughly as sqrt(2b * a_j0). It would be quite tedious to compute the time complexity exactly, so let's apply the above approximations from here on:

其中 a_n 替换 a_j0 t_n 是内部循环的运行时间–当然,总的时间复杂度只是 t_n 的总和。请注意,第一项由 n = 1 给出,并且 a 的输入值定义为 a_0

Where a_n replaces a_j0, and t_n is the run-time of the inner loop – and of course the total time complexity is just the sum of t_n. Note that the first term is given by n = 1, and that the input value of a is defined to be a_0.

在直接解决此重复项之前,请注意,由于第二项 t_2 已经与第一个 t_1 的平方根成比例,而后者在总和中占所有其他项。

Before directly solving this recurrence, note that since the second term t_2 is already proportional to the square root of the first t_1, the latter dominates all other terms in the sum.


因此,总时间复杂度仅为 O(sqrt(a / b))

The total time complexity is therefore just O(sqrt(a / b)).






更新:数值测试。


Update: numerical tests.

请注意,由于 a 的所有值变化均与 b 成正比,因此所有循环条件均为也与 b 成正比,可以通过设置 b = 1 规范化 并且只改变 a

Note that, since all changes in the value of a are proportional to b, and all loop conditions are also proportional to b, the function can be "normalized" by setting b = 1 and only varying a.

Javascript测试函数,它测量内部循环执行的次数:

Javascript test function, which measures the number of times that the inner loop executes:

function T(n)
{
   let t = 0, k = 0;
   while (n >= 1) {
      k = 1;
      while (n >= k) {
          n -= k;
          k++; t++;
      }
   }
   return t;
}

sqrt(n)$ c的图$ c>对 T(n)

令人信服的直线,确认时间复杂度的确是一半。

A convincing straight line which confirms that the time complexity is indeed half-power.