这个Prime查找算法的复杂性是多少?

时间:2018-02-12 00:12:08

标签: python algorithm time-complexity complexity-theory primes

我父亲和我正在努力确定我父亲作为一个年轻人想出的这个主要发现功能的算法复杂性。

第一个循环显然是n,因为它设置了字典。更棘手的部分是嵌套循环。外循环运行n / 4次:0 to n/2, step=2。内部循环仅在数字被认为是素数时才会运行,这在开始时会发生很多,但随着数字的增加会越来越少。

def primesV2(n):
    count = 0 # count is for counting the number of iterations done

    # set all even numbers (and 1) to False, else assume prime
    x = {}
    for i in range(n):
        if (i != 2 and i % 2 == 0) or i==1:
            x[i] = False
        else:
            x[i] = True

    # start at 3 because its the first odd prime
    i=3
    while i < n/2: # loop until halfway to n
        if x[i]: # if the number is considered prime
            for j in range(3*i,n,i*2): # if i=3, j will be 9,15,21 (odd multiples of 3)
                x[j] = False # these are not prime
                count = count + 1
        else:
            count = count + 1
        i = i+2

    return x, count

1 个答案:

答案 0 :(得分:0)

你在这里有一个改良的Eratosthenes筛子。没有任何优化,复杂性将是O(n log log n)。查看this wikipedia文章原因。

您的优化会使总速度提高4倍。您只能达到n / 2(您可以停在sqrt n)并跳过一半的倍数。虽然这将使代码更快,但复杂性保持不变(忽略常数因子)。所以它仍然是O(n log log n)

相关问题