Python while 循环查找素数

2024-04-29

作为 Python 的第一个练习,我尝试编写一个使用循环来查找素数的程序。一切都适用于 for 循环,所以我尝试使用 while 循环。这可行,但程序返回一些不正确的数字。

import math
# looking for all primes below this number
max_num = int(input("max number?: "))

primes = [2]  # start with 2
test_num = 3  # which means testing starts with 3

while test_num < max_num:
    i = 0
    # It's only necessary to check with the primes smaller than the square
    # root of the test_num
    while primes[i] < math.sqrt(test_num):
        # using modulo to figure out if test_num is prime or not
        if (test_num % primes[i]) == 0:
            test_num += 1
            break
        else:
            i += 1
    else:
        primes.append(test_num)
        test_num += 1

print(primes)

所以奇怪的是max_num=100它返回:

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

除了 9、25 和 49 之外,其他都是正确的,我不明白为什么。


您需要计算并包括平方根。否则,您的算法将错过素数平方族(9、25 和 49 是素数平方)。

快速解决方法是更换< with <=作为你的停止条件。

但考虑将停止条件更改为

primes[i] * primes[i] <= test_num

通过此测试,您不会陷入和脱离浮点。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python while 循环查找素数 的相关文章

随机推荐