简体   繁体   English

查找素数(缺少3!)

[英]Finding Prime Numbers (Missing 3!)

I came up with this solution to calculate probability of prime numbers in user defined die's sides. 我想出了这个解决方案来计算用户定义的模具侧面的质数概率。 But for some reason it doesn't like to include the number 3 only. 但是由于某种原因,它不希望只包含数字3。 Can anybody enlighten me why it hates number 3? 谁能启发我为什么讨厌3号?

Output is look like: [2, 5, 7, 11, 13, 17, 19, 23] --> Missing 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))

I would however expect: [2, 3, 5, 7, 11, 13, 17, 19, 23] 但是,我期望: [2, 3, 5, 7, 11, 13, 17, 19, 23]

You don't reset count here when you find a prime: 找到素数时,您无需在此处重置计数:

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

Which means that you can't find two primes in a row. 这意味着您不能连续找到两个素数。 That lever affects 3 since 2 is the only even prime. 该杠杆影响3因为2是唯一的偶数素数。 Just set count back to 0 whether or not you found a prime to fix it. 无论您是否找到修复它的质数,只需将count设置回0。 You can remove the else and don't need continue : 您可以删除else,而无需continue

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

You also don't need the else or continue inside your inner for loop since it doesn't do anything different than normal looping behaviour: 您也不需要else或在内部for循环内continue进行,因为它与正常的循环行为没有什么不同:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM