我知道,已经有很多关于素数的问题,但我不要求代码。我只是想知道,我的矿出了什么问题(我希望评论能帮助你理解我在做什么):
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() 工作正常。当 numbers=0 时,函数 primeNumbers 也可以正常工作。但是如果数字=1,那么,看起来,其中一个循环永远不会停止,我不明白为什么......