Finding the 1000th prime number (python) debug

Viewed 41

I am attempting to write a code to calculate the 1000th prime number and I'm running into an issue with my loop counter that i don't understand.

prime_test = 1
count=0
for count in range(0,1001):
    for divisor in range(2,prime_test):
        if (prime_test % divisor) == 0:
            break
    else:
        print(prime_test)
        count += 1
    prime_test+=1

Could someone please explain why the above code is dysfunctional? The problem is that the count variable iterates at the same rate as the prime_test variable. How do I separate the two such that count only increases when a new prime is found and not when the loop is engaged?

2 Answers

Don't use for count in range(0, 1001):. That just increments count sequentially, not when it finds a prime. Use a while loop.

prime_test = 2
count = 0
while count < 1000:
    for divisor in range(2,prime_test):
        if (prime_test % divisor) == 0:
            break
    else:
        print(prime_test)
        count += 1
    prime_test += 1

You also should start prime_test at 2, not 1, since 1 isn't a prime number, but your algorithm will say it is.

One more answer as the same thing might need to be repeated thousand times before it could be understood.

Setting the value of c before the loop has no effect at all and the new to c within the loop assigned value will be overwritten by next loop loop as c will be set to the next value provided by range(). Python for c in range() loops are not like loops in some other programming languages. So every newbie has to go through this ... wondering how it comes.

Following code demonstrates this:

c = 100
for c in range(5):
    print(c, end=' -> ')
    c = c + 5
    print(c)

printing

0 -> 5
1 -> 6
2 -> 7
3 -> 8
4 -> 9


If you change your code to:

prime_test = 2
counter=0
for count in range(0,11):
    for divisor in range(2, prime_test):
        if (prime_test % divisor) == 0:
            break
    else:
        print(prime_test)
        counter += 1
    prime_test+=1
print(f'{counter=} , {prime_test=} ')

you will get as output:

2
3
5
7
11
counter=5 , prime_test=13
Related