【发布时间】:2016-04-12 08:52:30
【问题描述】:
作为 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,我不知道为什么。
【问题讨论】:
-
primes[i] <= math.sqrt(test_num) -
你注意到数字是奇数吗?
-
一个
while ... else!记得当它进入else时玩得开心:)(我不了解其他人,但我一直避免while-else和for-else并且从未在其他人的代码中看到它们;他们觉得不直观)
标签: python python-3.x while-loop primes