python素数错误

时间:2016-02-18 17:19:20

标签: python

这个问题要求1-25的素数,这是我的代码,它出错了。任何人都可以帮助我PLZ ???非常感谢你!

n=1
f=0
while n<=25:
    for i in range(2,n):
        if n%i==0:
            f+=1
        else:
            f
    if f==0:
        print str(n) + "is a prime number"
    else:
        print str(n) + "is not a prime number"
    n+=1

2 个答案:

答案 0 :(得分:2)

您没有重新设置f的值,因此一旦您点击非素数,其后的所有数字都将被报告为非素数。

n=1
f=0
while n<=25:
    for i in range(2,n):
        if n%i==0:
            f+=1
        else:
            f
    if f==0:
        print str(n) + "is a prime number"
    else:
        print str(n) + "is not a prime number"
    f = 0
    n+=1

你的方式效率也很低,你应该从2开始,而不是1.此外,3之后的所有素数都是6n-1或6n + 1的形式(其中n是整数)。所以你不需要测试所有的数字。如果数字是否为素数,只需测试数字6n-1和6n + 1.

答案 1 :(得分:0)

我已经重新安排了您的代码,以提高效率。它首先测试n是否为偶数,然后测试奇数因子直到n的平方根,因为如果n不是素数,它必须有一个因子&lt; =它平方根。 (你能明白为什么吗?)

为了简化逻辑,我已将测试转移到一个函数中。

如果找到n因子,我们会立即从函数返回,因为没有必要寻找更多因素。

def prime_test(n):
    if n % 2 == 0:
        return False
    for i in range(3, int(n**0.5 + 1), 2):
        if n % i == 0:
            return False
    return True

print 2, "is a prime number"

for n in range(3, 26):
    if prime_test(n):
        print n, "is a prime number"
    else:
        print n, "is not a prime number"

<强>输出

2 is a prime number
3 is a prime number
4 is not a prime number
5 is a prime number
6 is not a prime number
7 is a prime number
8 is not a prime number
9 is not a prime number
10 is not a prime number
11 is a prime number
12 is not a prime number
13 is a prime number
14 is not a prime number
15 is not a prime number
16 is not a prime number
17 is a prime number
18 is not a prime number
19 is a prime number
20 is not a prime number
21 is not a prime number
22 is not a prime number
23 is a prime number
24 is not a prime number
25 is not a prime number