0

I feel truly ashamed to not be able to figure this one out but this is killing me! I don't understand why my while loop condition isn't working. Based on the range in the initial for loop, I'm getting a variable number of terms (above 10001) after crossing the 105000 for the second number in range.

prime = []

terms = 10001
length = 0

while length <= terms:

    for i in range(2, 110000): 
        isPrime = True

        for j in range(2, int(i**0.5) + 1): 
            if i%j == 0: 
                isPrime = False
                break

        if isPrime:
           prime.append(i)
    
    length = len(prime)

print(length)

And the output turns out to be

10024

I tried using len(prime) initially and then created the variable length, as expected, it made no difference.

Please nudge me in the right direction to fix this error. 😫

1 Answer 1

1

You're not testing the length value against terms inside your outer for loop, so it will always return all the primes up to the end of the range. You need to add that check into that loop. For example:

prime = []    
terms = 10001

for i in range(2, 110000): 
    isPrime = True

    for j in range(2, int(i**0.5) + 1): 
        if i%j == 0: 
            isPrime = False
            break

    if isPrime:
       prime.append(i)
    
    if len(prime) == terms:
        break

print(len(prime))

Output:

10001

Note you can simplify your code (removing the isPrime flag) by taking advantage of an else clause on your for loop:

for i in range(2, 110000): 
    for j in range(2, int(i**0.5) + 1): 
        if i%j == 0: 
            break
    else:
       prime.append(i)
    
    if len(prime) == terms:
        break
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for pointing this out to me. I'm now one more step familiar with python's nuances.
I was wondering how this else clause works when there isn't an if clause aligned to it at the top in the first place. Isn't that a necessary thing for an else statement? @Nick
@SachinKrishna no, in python a for loop can have an else clause; it is executed if there is no break from the for loop. See the manual it has an example just like your code

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.