简体   繁体   English

确定带有中断的循环的大O

[英]Determining Big O of a loop with a break

Given a function like this to find a prime number: 给定这样的函数来查找素数:

function find_the_prime(number) {
  var found = false;
  for(var i = 0; i < number; i++) {
    if(number%i == 0) {
      found = true; 
      break;
    }
  }  
  return found;
}

Without the break, the function in the best case is O(1), in the worst case is O(n) and the general case O(n). 没有中断,最佳情况下的函数为O(1),最坏情况下的函数为O(n),一般情况下的函数为O(n)。

Can you explain how the break affects big o? 您能解释一下休息时间如何影响大o吗? Does it at all? 有没有

Your code is O(1) for the trivial reason that it will always quit on the second loop because number%1 == 0. 您的代码为O(1)的原因很简单,因为number%1 == 0,它将始终在第二个循环中退出。

If you correct your code to: 如果您将代码更正为:

for(var i = 2; i < number; i++) {

Then it'll be O(n) for the same reason the @zmf said. @zmf表示相同的原因,那么它将是O(n)。

And without the break, it would more correctly be called O(n) even for the "best-case" because it still scales with the input. 而且,即使没有“中断”,它也将更正确地称为O(n) ,因为它仍然随输入缩放。 The smallest input isn't "best-case" or else all algorithms would be trivially best-case O(1) . 最小的输入不是“最佳情况”,否则所有算法都是琐碎的最佳情况O(1)

So it's O(n) without the break and O(n) with the break, but that doesn't mean it isn't obviously better and faster with the break. 因此,它是不带中断的O(n)带中断的O(n) ,但这并不意味着带中断显然不是更好,更快。 The big-O notation is about how an algorithm scales with the size of the input, not (necessarily) how fast it is. big-O表示法是关于算法如何根据输入的大小缩放,而不是(有必要)快速地缩放。 Sometimes an O(n) algorithm might be faster than an O(log n) algorithm for a particular input. 对于特定的输入,有时O(n)算法可能比O(log n)算法更快。

This is still O(N), even if thats the worst case, O(N) is how you'd refer to this algorithm. 即使那是最坏的情况,它仍然是O(N),O(N)是您引用此算法的方式。 Its growth rate is still dependent on N. 它的增长率仍然取决于N。

(If you fix the bug that is) (如果您修复的错误是)

Actually, funny enough, your answer is O(1). 实际上,很有趣,您的答案是O(1)。 No matter what number you put in (as long as it's > 0), it'll always break at 1 无论您输入什么数字(只要它大于0),它总是会在1处中断

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM