Python 质数集合

1 投票
2 回答
517 浏览
提问于 2025-04-17 21:52

我正在尝试写一个程序,目的是打印出一组数字中的所有质数。当我运行下面写的程序时,结果只返回了2和3,之后就没有更多的输出了。我的程序中有什么地方导致了这个问题呢?

def main():
    for i in range (2, 100):  #the set of numbers from which 
        if is_prime(i):       #we want our prime numbers
            print(i)

def is_prime(i):
    prem = int((i**.5)+1)               #prem is square root plus one
    for pcheck in range (2, prem):      #of i, the counter in our number set
        if i/pcheck == int(i/pcheck):
        #^numbers evenly divisible by other numbers return false
            return False
    #if they don't, it's true
    return True

main()

2 个回答

0

如果你想检查除法的结果是整数还是小数,我建议你使用下面的代码。

def is_prime(i):
    prem = int((i**.5)+1)               #prem is square root plus one
    for pcheck in range (2, prem):      #of i, the counter in our number set
        if str(float(i)/pcheck).endswith(".0"):
        #confirm whether the float answer ends with .0 or not
            return False
    #if they don't, it's true
    return True

str(float(i)/pcheck).endwith(".0")

如果除法的结果是以 .0 结尾的,这个代码会返回 True。

比如说,

1.0/3 = 0.3333333333333333 In this case return False
10.0/5 = 2.0               In this case return True

最后,这些代码,包括你的 main() 函数,会返回 1 到 100 之间的所有质数。

3

你这个判断质数的函数有问题。

i/pcheck == int(i/pcheck)

这一行在左边的部分已经是整数了(在 Python 2.x 版本中)。

在你的代码最上面加上 from __future__ import division,你会看到不同的结果!

撰写回答