🛠️ToolsShed

素数筛

使用埃拉托斯特尼筛法找出给定范围内的所有素数。在网格中可视化素数。

25
找到的素数
99
检查的数字
25.3%
素数密度

数字网格(素数高亮)

23456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100

高亮 = 素数

素数

2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97

常见问题

代码实现

def sieve_of_eratosthenes(limit: int) -> list[int]:
    """Return list of all primes up to limit."""
    if limit < 2:
        return []
    is_prime = [True] * (limit + 1)
    is_prime[0] = is_prime[1] = False
    i = 2
    while i * i <= limit:
        if is_prime[i]:
            for j in range(i * i, limit + 1, i):
                is_prime[j] = False
        i += 1
    return [n for n, p in enumerate(is_prime) if p]

primes = sieve_of_eratosthenes(100)
print(primes)
# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, ...]
print(f"Count: {len(primes)}")  # Count: 25

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.