在python中使用遍历循环求素数_Python while循环查找素数

作为使用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,我不知道为什么。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值