python - Python初学者问题“质数计数”
问题描述
def prime_count(a, b):
for i in range(a,b):
if i % 2 != 0:
return sum(i)
else:
return 0 "
我是一名初级程序员,我一直在练习 Edabit 上的一些挑战,小问题但需要一些思考(对我来说)。我正在尝试计算有多少个素数a
,b
它们已经是整数并且没有用户输入。
我还不太擅长循环,并认为这将是一个很好的练习挑战,我做错了什么?我不断得到int object is not iterable
如果需要参考,这里是挑战的链接。链接:https ://edabit.com/challenge/6QYwhZstMuHYtZRbT
解决方案
正如人们在评论部分所说,调用sum()
是导致错误的原因。
但是,即使你以某种方式把那部分弄对了,你也不会完全得到你想要的。也许您只是在尝试一个简单的 for 循环来检查数字是否为奇数......?
无论如何,我通常喜欢使用埃拉托色尼筛法来生成素数,因为它很简单。
def sieve_of_eratosthenes(start, end):
if start > end:
raise AssertionError
# end = end + 1 # If end is inclusive, then uncomment this line.
if end < 2:
return 0
sieve = [i for i in range(2, end)] # Initialize an array of number from 2 to end.
size = len(sieve)
p = 2 # Initial prime.
count = 0
# This block implements Sieve of Eratosthenes.
while count < size:
for i in range(count, size):
num = sieve[i]
if num != p and num % p == 0:
sieve[i] = 0
if count == size-1:
break
count += 1
while sieve[count] == 0:
count += 1
if count == size-1:
break
p = sieve[count] # Update the next prime.
# This block calculates the numbers of primes between start and end.
num_of_primes = 0
for p in sieve:
if p == 0 or p < start:
continue
num_of_primes += 1
print(sieve)
return num_of_primes
sieve_of_eratosthenes(1, 100) # This should return 25.
推荐阅读
- mysql - Vitess 远程连接访问被拒绝问题
- mysql - xampp 上的 mysql 问题
- node.js - MongoDb 重复密钥错误
- java - 如何使用 selenium java 上传文件
- python - 对于大小为 795 的轴 0,索引 795 超出范围
- linux - 我可以从哪里开始进入网络和黑客领域的旅程?
- sql - 大型 SQL“IN”子句和数百万行的快速结果
- websocket - 向服务器发送数据时出现 Python Flask Socketio BadNamespaceError
- mysql - MySQL查询没有给我平均的,饱和的未知列
- android - Android Kotlin 协程在使用变量打开的片段上创建 RecyclerView