Этот код очень запутан, и я не могу точно понять, о чем вы думали, когда писали его, или что вы пытались достичь. Первое, что я хотел бы предложить при попытке выяснить, как кодировать, - это начать с того, чтобы сделать имена переменных чрезвычайно наглядными. Это поможет вам получить представление о том, что вы делаете прямо в голове, а также всем, кто пытается помочь вам показать вам, как правильно сформулировать свои идеи.
При этом, вот пример программы, которая выполняет что-то близкое к цели:
primewanted = int(input("This program will give you the nth prime.\nPlease enter n:"))
if primewanted <= 0:
print "n must be >= 1"
else:
lastprime = 2 # 2 is the very first prime number
primesfound = 1 # Since 2 is the very first prime, we've found 1 prime
possibleprime = lastprime + 1 # Start search for new primes right after
while primesfound < primewanted:
# Start at 2. Things divisible by 1 might still be prime
testdivisor = 2
# Something is still possibly prime if it divided with a remainder.
still_possibly_prime = ((possibleprime % testdivisor) != 0)
# (testdivisor + 1) because we never want to divide a number by itself.
while still_possibly_prime and ((testdivisor + 1) < possibleprime):
testdivisor = testdivisor + 1
still_possibly_prime = ((possibleprime % testdivisor) != 0)
# If after all that looping the prime is still possibly prime,
# then it is prime.
if still_possibly_prime:
lastprime = possibleprime
primesfound = primesfound + 1
# Go on ahead to see if the next number is prime
possibleprime = possibleprime + 1
print "This nth prime is:", lastprime
Этот бит кода:
testdivisor = 2
# Something is still possibly prime if it divided with a remainder.
still_possibly_prime = ((possibleprime % testdivisor) != 0)
# (testdivisor + 1) because we never want to divide a number by itself.
while still_possibly_prime and ((testdivisor + 1) < possibleprime):
testdivisor = testdivisor + 1
still_possibly_prime = ((possibleprime % testdivisor) != 0)
может быть заменено несколько медленным, но, возможно, более понятным:
# Assume the number is prime until we prove otherwise
still_possibly_prime = True
# Start at 2. Things divisible by 1 might still be prime
for testdivisor in xrange(2, possibleprime, 1):
# Something is still possibly prime if it divided with a
# remainder. And if it is ever found to be not prime, it's not
# prime, so never check again.
if still_possibly_prime:
still_possibly_prime = ((possibleprime % testdivisor) != 0)