倒计时和素数检查

时间:2014-06-09 05:44:08

标签: python-2.7

我正在尝试编写一个函数,如果一个人插入一个值,它会倒数到0,它会显示每个数字是否为素数。

def pn(n):
     while n > 0:
         #print (n)
         if n == 1:
             print '1 is a special number'
         elif n == 2:
             print '2 is EVEN and PRIME number'
         else:
             v_rem = n%2
             v_half = int(n/2)

             if v_rem == 0:
                 print n, ' is EVEN number'
             elif v_rem == 1:
                 print n, ' is ODD number'
                 i = 2
                 v_is_prime = "y"

                 while i <= v_half:
                     v_prim_rem=n%i
                     if v_prim_rem == 0:
                        print n, ' is not a prime number'
                        v_is_prime = "n"
                        break
                     i = i + 1
                     if v_is_prime == "y":
                         print n, 'is a prime number'
         n = n-1

1 个答案:

答案 0 :(得分:0)

据推测,您的担忧与输出错误有关:

10  is EVEN number
9  is ODD number
9 is a prime number # here
9  is not a prime number
8  is EVEN number
7  is ODD number
7 is a prime number
7 is a prime number # and here
6  is EVEN number
5  is ODD number
5 is a prime number
4  is EVEN number
3  is ODD number
2 is EVEN and PRIME number
1 is a special number

您的缩进是错误的:v_is_prime的检查应该之外循环v_half,因此应该缩减一步:

v_is_prime = "y"
while i <= v_half:
    v_prim_rem=n%i
    if v_prim_rem == 0:
        print n, ' is not a prime number'
        v_is_prime = "n"
        break
    i = i + 1
if v_is_prime == "y":
    print n, 'is a prime number'

或者,您可以使用else来处理此问题并删除标记(应该是布尔值TrueFalse而不是字符串'y'和{{1如果你保留它):

'n'

但是,如果您可以使用while i <= v_half: if v_n % i == 0: print n, ' is not a prime number' break i = i + 1 else: # i.e. didn't 'break' print n, 'is a prime number' 循环,请不要使用while循环:

for

for n in range(n, 0, -1):
     ...

您也可以采用字符串格式:

for i in range(int(n/2)):
     ...
else:
    ...

最后,这个问题非常适合Sieve of Erastosthenes

print "{0} is a prime number".format(n)