2012-01-03 8 views
1

python에서 프로그램을 사용하여 처음 1000 소수 (2 제외)를 인쇄합니다. 출력을 위해 얻을 수있는 모든 것은 3 번입니다. 루프가 끝나는 곳이나 시점을 이해하지 못합니다. 매우 프로그래밍에 새로운. 아무도 도와 줄 수 있니? 당신이 isPrimeFalse으로 설정 한 후에는 내부 while 루프에서 결코 있도록중첩 된 while 루프가 작동하지 않는 이유

primeCounter = 1 
candidate = 3 

while primeCounter < 1000: 
    isPrime = True 
    counter = 2 
    while counter < candidate: 
     if candidate%counter == 0: 
      isPrime = False 
     else: 
      counter = counter + 1 

    if isPrime == True: 
     print candidate 
     primeCounter = primeCounter + 1 

    candidate = candidate + 1 
+0

디버깅을 시도한 적이 있습니까? 조건문 등을 테스트 한 변수의 값을 출력하도록함으로써? –

답변

3
primeCounter = 1 
candidate = 3 

while primeCounter < 1000: 
    isPrime = True 
    counter = 2 
    while counter < candidate: 
     if candidate%counter == 0: 
      isPrime = False 
      break # <<<<<<<<<<<<<<<<< break here, or the loop will go infinite 
     else: 
      counter = counter + 1 

    if isPrime == True: 
     print candidate 
     primeCounter = primeCounter + 1 

    candidate = candidate + 1 
+0

은 이제 완벽하게 작동합니다. 이 또한 – patch321

2

, 당신은 다시 counter를 증가하지 않았다. 하지 후보자 % 카운터 경우

while counter < candidate: 
    if candidate%counter == 0: 
     isPrime = False 

블록

에서

+0

고마워요. 고맙습니다 – patch321

0

귀하의 문제는, 당신은 무한 루프를 얻을.

관련 문제