首页 > 解决方案 > Python初学者问题“质数计数”

问题描述

def prime_count(a, b):
    for i in range(a,b):
        if i % 2 != 0:
            return sum(i)
        else:
          return 0 "

我是一名初级程序员,我一直在练习 Edabit 上的一些挑战,小问题但需要一些思考(对我来说)。我正在尝试计算有多少个素数ab它们已经是整数并且没有用户输入。

我还不太擅长循环,并认为这将是一个很好的练习挑战,我做错了什么?我不断得到int object is not iterable

如果需要参考,这里是挑战的链接。链接:https ://edabit.com/challenge/6QYwhZstMuHYtZRbT

标签: pythonfunctionloops

解决方案


正如人们在评论部分所说,调用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.

推荐阅读