【问题标题】:What is the time and space complexity of this code? I'm very confused on this subject so I am asking这段代码的时间和空间复杂度是多少?我对这个问题很困惑,所以我问
【发布时间】:2022-07-06 13:06:22
【问题描述】:

这是我的代码,它是俄罗斯农民乘法算法。我发现时间和空间的复杂性非常令人困惑,所以我需要一些帮助。

这也适用于java语言

谢谢。

int num1 = Integer.parseInt(jTextField1.getText());
int num2 = Integer.parseInt(jTextField2.getText());


int res=0;

 // While second number doesn't become 1

    while (num2 > 0)

    {

         // If second number becomes odd, 

         // add the first number to result

         if ((num2 & 1) != 0)

             res = res + num1;



        // Double the first number 

        // and halve the second number

        num1 = num1 << 1;

        num2 = num2 >> 1;

    }

   jTextField3.setText(String.valueOf(res));
}

【问题讨论】:

    标签: java time-complexity space-complexity


    【解决方案1】:

    如果num2 大于零,循环将继续执行。在循环的每次迭代之后,num2 减半。这意味着循环将执行log_2(num2) 次。所以,假设num2用N表示,我们可以说这个循环的复杂度是log_2(N)。

    【讨论】:

      猜你喜欢
      • 2023-01-12
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2023-02-26
      • 1970-01-01
      • 2015-03-31
      • 2022-11-14
      • 1970-01-01
      相关资源
      最近更新 更多