【问题标题】:How to compute time complexity when using a mod operation使用 mod 操作时如何计算时间复杂度
【发布时间】:2020-06-04 08:21:58
【问题描述】:

我正在尝试找出以下代码的时间复杂度。

N= number of elements in array
D= a constant: D>1
V= a constant: V>1000

counter=1; //the maximum value of the counter is N/D.
for(i=0; i<N; i++)
{
    [OP1]   O1_Operation;        // O(1) operation.   [Total: N times]
    [OP2]   if(i%D!=0) continue; // O(1) operation.   [Total: N times]

    [OP3]   for(j=0;j<counter;j++) //                 [Total: {(N/D)*((N/D)+1)}/2 times] 
    [OP4]        for(s=0;s<V;s++)
    [OP5]            O1_Operation; // O(1) operation. [Total: (V*{(N/D)*((N/D)+1)}/2) times] 

    [OP6]   counter++;             // O(1) operation. [Total: N/D times]
 }

我添加了每个操作的时间复杂度和它将执行的总次数。这段代码让我感到困惑是因为 mod 操作。这个模组将只允许(N/D)操作来完成代码 OP[3-6]。

对于 [OP3],第一次执行 1 次,第二次执行 2 次,...,N/D 次。因此,执行的总数可以是 [(N/D) * ( (N/D)+1)] /2。因为 D 和 V 是常量而删除它们会导致整个代码的复杂度为 O(N^2)。

这对吗?

【问题讨论】:

  • 好吧,最坏情况的复杂性很简单:O(N * N/D * V)
  • 并且可以进一步将N * N/D部分限制为N/D * (N/D + 1) / 2

标签: algorithm time-complexity complexity-theory


【解决方案1】:

这取决于 V 和 D 的性质,但您的整体时间复杂度分析是正确的,您的结论可能是 O(VN^2/D^2) 或 O(N^2),具体取决于您的方式查看 V 和 D 以及问题/问题的性质。

【讨论】:

    猜你喜欢
    • 2021-01-08
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多