python找出N以内的所有质数

2022-05-03 00:00:00 python 找出 质数
"""
皮蛋编程(https://www.pidancode.com)
创建日期:2022/4/23
功能描述:python找出N以内的所有质数
"""
max = int(input("Find primes up to what number? : "))
primeList = []
# for loop for checking each number
for x in range(2, max + 1):
    isPrime = True
    index = 0
    root = int(x ** 0.5) + 1

    while index < len(primeList) and primeList[index] <= root:
        if x % primeList[index] == 0:
            isPrime = False
            break
        index += 1

    if isPrime:
        primeList.append(x)

print(primeList)

输出:

Find primes up to what number? : 20
[2, 3, 5, 7, 11, 13, 17, 19]

相关文章