用python计算素数

时间:2012-05-05 12:50:49

标签: python

我知道,关于素数已有很多问题,但我不要求代码。我只是想知道,我的错误(我希望评论能帮助你理解我正在做的事情):

from math import ceil

def isPrimeNumber (n, out='short'): #Checks, whether n is a prime number
    answer = 'Yes'
    for p in range(2, int(ceil(n**0.5))+1): #Checks all numbers lower than 
                                            #SQRT(n), if they are divisors of n
        if n%p == 0:    #If p is a divisor, n isn't prime
            answer = 'No'  
            if out == 'verbose':
                print 'Least divisor is', p
            return False
            break
    if answer == 'Yes': #If there isn't a p, that is a divisor, n is prime
        if out == 'verbose':
            print 'No divisors except for 1 and', str(n)+'!'
        return True   

def primeNumbers (start = 1, stop = 1000, numbers = 0):
    N = stop
    if numbers == 0: #Calculates all prime numbers in N numbers in a row
                     #(N=1000 -> calculates all prime numbers in 1000 numbers,
                     #by default from 1 to 997)
        primes = []
        for i in range(start, N+1):
            if isPrimeNumber(i) == True:
                primes.append(i)
    elif numbers == 1: #Calculates N prime numbers in a row 
                       #(N=1000 -> calculates 1000 prime numbers)
        primes = [start]
        i = len(primes)
        j = 1
        while i <= N: #Stops, when we get N prime numbers - doesn't work!
            n = max(primes) + 1
            while j != 'stop':
                if isPrimeNumber(n, out='short') == True:
                    primes.append(n)
                    i = i + 1
                    j = 'stop' #Stops nested cycle, when reached 
                               #the first prime number
                else:
                    n = n + 1
    else:
        print 'Wrong input! 3rd number in function call must be either 0 or 1'
    return primes

函数isPrimeNumber()工作正常。当数字= 0时,函数primeNumbers也可以正常工作。但是如果数字= 1,那么,看起来,其中一个周期永远不会停止,我不能理解为什么......

3 个答案:

答案 0 :(得分:2)

你在这里有一个无限循环:

    while i <= N:
        n = max(primes) + 1 ### resetting `n'!
        while j != 'stop':
            if isPrimeNumber(n, out='short') == True:
                ...
                j = 'stop'
            else:
                n = n + 1

j设置为'stop'后,您永远不会将其更改回来。一旦发生这种情况,内部while实际上变为无操作,将外部while转变为无限循环。

答案 1 :(得分:1)

问题是你的j变量最终设置为'stop',然后再也不会再次设置,所以while j!='stop'只能在第一次运行。

    # don't initialize j here
    while i <= N: #Stops, when we get N prime numbers - doesn't work!
        n = max(primes) + 1
        j = 1  #initialize it here
        while j != 'stop':
            if isPrimeNumber(n, out='short') == True:
                primes.append(n)
                i = i + 1
                j = 'stop' #Stops nested cycle, when reached 
                           #the first prime number
            else:
                n = n + 1

答案 2 :(得分:0)

我只是觉得我要清理一下......

from math import ceil
def isprime (n,out="short"):
    answer = True
    for p in range(2,int(ceil(n ** 0.5)) + 1):
        if n % p == 0:
            answer = False
            if out == "verbose":
                print "Least Divisor: " + str(p)
            return False
    if answer:
        if out == "verbose":
            print "No Divisors (Except For 1 & " + str(n) + "!"
        return True
def primenumbers (start = 1,stop = 1000,numbers = False):
    N = stop
    if numbers:
        primes = [start]
        i = len(primes)
        j = 1
        while i <= N:
            n = max(primes) + 1
            j = true
            while j:
                if isPrimeNumber(n):
                    primes.append(n)
                    i = i + 1
                    j = false
                else:
                    n = n + 1
    else
        primes = []
        for i in range(start,N + 1):
            if isPrimeNumber(i):
                primes.append(i)
    return primes

我确实稍微改变了实际程序。