埃拉托斯特尼筛法(Sieve of Eratosthenes)是一种用于找到一定范围内所有素数的算法。下面是一个实现该算法并进行比较的示例代码:
import time
def sieve_of_eratosthenes(n):
    primes = [True] * (n+1)
    primes[0] = primes[1] = False
    p = 2
    while p * p <= n:
        if primes[p]:
            for i in range(p*p, n+1, p):
                primes[i] = False
        p += 1
    return [i for i in range(n+1) if primes[i]]
def test_sieve_of_eratosthenes(n):
    start_time = time.time()
    primes = sieve_of_eratosthenes(n)
    end_time = time.time()
    execution_time = end_time - start_time
    print(f"Primes less than or equal to {n}:")
    print(primes)
    print(f"Execution time: {execution_time} seconds")
test_sieve_of_eratosthenes(100)
在上面的代码中,sieve_of_eratosthenes函数使用布尔数组 primes 来表示是否为素数。首先,将所有元素都初始化为 True。然后,从2开始,将素数的倍数标记为 False。最后,返回所有为 True 的索引,即为素数。
test_sieve_of_eratosthenes函数用于测试 sieve_of_eratosthenes 函数,并打印出素数列表以及算法的执行时间。
运行上述代码,将输出小于或等于100的素数列表,并显示算法的执行时间。
请注意,为了更好地比较算法的执行时间,您可以尝试不同的输入大小,并比较它们的执行时间。
                    上一篇:埃拉托斯特尼筛法的O(n)实现
                
下一篇:埃拉托斯特尼筛法的运行时