查找素数(缺少3!)

时间:2019-02-11 17:21:53

标签: python

我想出了这个解决方案来计算用户定义的芯片侧面的质数概率。但是由于某种原因,它不希望只包含数字3。有人能启发我为什么讨厌3号吗?

输出如下所示: [2, 5, 7, 11, 13, 17, 19, 23]->缺少3个!

def cal_probability (event, sample_space):
    return len(event)/ len(sample_space)

def cal_prime_numbers (s_space):
    count = 0
    prime_nums = []
    for num in s_space:
        for i in s_space:
            if num % i == 0:
                count += 1
            else:
                continue
        if count == 2:
            prime_nums.append (num)
        else:
            count = 0
            continue
    return prime_nums

if __name__ == '__main__':
    sides = input ('Enter the number of sides: ')
    sample_space = list (range (1, int(sides)+1))
    print (sample_space)
    event = cal_prime_numbers (sample_space)
    print (event)
    p = cal_probability (event, sample_space)
    print ('The probabilty of prime numbers to happen in {0} sides die is: {1}%'.format (sides, p*100))

但是我希望: [2, 3, 5, 7, 11, 13, 17, 19, 23]

1 个答案:

答案 0 :(得分:4)

找到素数时,您无需在此处重置计数:

if count == 2:
    prime_nums.append (num)
else:
    count = 0
    continue

这意味着您不能连续找到两个素数。该杠杆会影响3,因为2是唯一偶数。无论您是否找到修复它的质数,只需将count设置回0。您可以删除else并不需要continue

if count == 2:
    prime_nums.append (num)
count = 0

您也不需要内部for循环中的elsecontinue,因为它与正常的循环行为没有什么不同:

def cal_prime_numbers (s_space):
    count = 0
    prime_nums = []
    for num in s_space:        
        for i in s_space:    
            if num % i == 0:
                count += 1
        if count == 2:
            prime_nums.append (num)
        count = 0
    return prime_nums