简体   繁体   English

这段代码的复杂程度(Big O)是多少

[英]What's the order of complexity (Big O) of this code

I initially thought the complexity is O(n^3) because the inner loop goes to i*i, but now I think the complexity is O(n^2) because of the "break" statement. 我最初认为复杂度是O(n ^ 3),因为内部循环转到i * i,但现在我认为复杂性是O(n ^ 2),因为“break”语句。

What's your thought? 你觉得怎么样?

#include <stdio.h>

int main()
{
    int i,k,l,m;
    unsigned int j;
    l=0;
    for (i=3; i<65535;i+= 2) {
        k=1;
        for (j=3; j <= i*i; j += 2) {
            if (j==i) continue;
            if(i%j ==0) {
                k=0;
                break;
            }
         }
         if (k) { l++; }
     }
     printf("%i\n", l);
     return 0;
}

The inner loop is O(N^2) for prime numbers but fast for non-primes (worst case O(N^1/2) because you only have to search up to sqrt(N)). 对于素数,内环是O(N ^ 2),对于非素数,内环是快的(最坏的情况是O(N ^ 1/2),因为你只需要搜索到sqrt(N))。

The number of prime numbers, however, is small compared to the number of non-primes. 然而,与非素数相比,素数的数量很少。 An approximation of the number of primes to up X is: X / log(X), as found in this reference link. 向上X的素数的近似值是:X / log(X),如此参考链接中所示。

So throwing out the non-primes as inconsequential, there are N / log(N) primes and each inner loop takes O(N^2) time, so the total time is O(N^3 / log(N)). 因此抛出非素数是无关紧要的,有N / log(N)素数,每个内部循环需要O(N ^ 2)时间,因此总时间为O(N ^ 3 / log(N))。

for (j=3; j <= i*i; j += 2) { if (j==i) continue; if(i%j ==0) { k=0; break; } }

Without j == i 没有j == i

here j=3,5,7,9,11,13,15,17....65535. 这里j = 3,5,7,9,11,13,15,17 ...... 65535。 That means j will contain all the prime numbers upto 65535 other than 2. Lets have a Math here. 这意味着j将包含除了2之外的所有素数达到65535.这里有一个数学。 j< i*i . j <i * i。 if i is a power of 2 or a prime number, then j loop will get executed completely, but we can neglect power of 2 as i is always odd.so for any i , at some point i=j [ O(n) complexity ] 如果i是2的幂或素数,则j循环将完全执行,但我们可以忽略2的幂,因为我总是奇数。对于任何i,在某些点i = j [ O(n)复杂度]

If i is a consonant then i % j == 0 will happen quickly . 如果我是一个辅音,那么i%j == 0将很快发生。 As pointed out by JS1 , the j loop will take n/logn by neglecting j == i . 正如JS1所指出的那样,j循环将通过忽略j == i来取n / logn。

So total time complexity = O(N*2 / logn ) 所以总时间复杂度= O(N * 2 / logn)

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

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