python找素数程序_使用Python查找第n个素数

这篇博客探讨了一位初学者在Python中使用循环寻找素数的问题。代码示例展示了如何通过递增测试判断一个数是否为素数,但遇到了输出格式不正确的问题。尽管不是最优化的解决方案,它有助于理解基础循环概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当我运行这段代码时,即使只计算到第10个素数(而不是1000),我得到一个偏斜/顶部输出 – 我的is_composite变量的所有“非素数”标题,我的test_num给出了素数和复合数,我的prime_count已关闭

开发人员共享的一些答案使用函数和数学导入 – 这是我们尚未涉及的内容.我不是想要得到最有效的答案;我只是想编写可行的python代码来理解循环的基础知识.

# test a prime by diving number by previous sequence of number(s) (% == 0). Do this by

# counting up from 1 all the way to 1000.

test_num = 2 #these are the numbers that are being tested for primality

is_composite = 'not prime' # will be counted by prime_count

prime_count = 0 #count the number of primes

while (prime_count<10): #counts number primes and make sures that loop stops after the 1000th prime (here: I am just running it to the tenth for quick testing)

test_num = test_num + 1 # starts with two, tested for primality and counted if so

x = test_num - 1 #denominator for prime equation

while (x>2):

if test_num%(x) == 0:

is_composite = 'not prime'

else:

prime_count = prime_count + 1

x = x - 1

print is_composite

print test_num

print prime_count

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值